umf-access 0.1.0.dev8__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (117) hide show
  1. umf_access/__init__.py +109 -0
  2. umf_access/adoption.py +41 -0
  3. umf_access/build/__init__.py +2 -0
  4. umf_access/build/approximate.py +34 -0
  5. umf_access/build/catalog.py +1626 -0
  6. umf_access/build/commands.py +394 -0
  7. umf_access/build/pg_privileges.py +1544 -0
  8. umf_access/build/privileges.py +134 -0
  9. umf_access/build/search.py +365 -0
  10. umf_access/build/unity_search.py +104 -0
  11. umf_access/bulk.py +227 -0
  12. umf_access/canonical.py +23 -0
  13. umf_access/capture.py +410 -0
  14. umf_access/catalog.py +325 -0
  15. umf_access/codec_support.py +427 -0
  16. umf_access/commands.py +93 -0
  17. umf_access/delta_read.py +758 -0
  18. umf_access/dsl/__init__.py +148 -0
  19. umf_access/dsl/_context.py +36 -0
  20. umf_access/dsl/_expressions.py +625 -0
  21. umf_access/dsl/_joined.py +4 -0
  22. umf_access/dsl/_nodes.py +207 -0
  23. umf_access/dsl/_query.py +5559 -0
  24. umf_access/dsl/_selection.py +143 -0
  25. umf_access/dsl/navigation.py +302 -0
  26. umf_access/dsl/render.py +516 -0
  27. umf_access/dsl/search.py +343 -0
  28. umf_access/engine_catalog.py +563 -0
  29. umf_access/generated_core.py +5 -0
  30. umf_access/lifecycle/__init__.py +46 -0
  31. umf_access/lifecycle/_darwin_process_observer.c +306 -0
  32. umf_access/lifecycle/approval.py +366 -0
  33. umf_access/lifecycle/backfills.py +79 -0
  34. umf_access/lifecycle/catalog.py +289 -0
  35. umf_access/lifecycle/cli.py +231 -0
  36. umf_access/lifecycle/concurrent.py +196 -0
  37. umf_access/lifecycle/conversion_policy.py +188 -0
  38. umf_access/lifecycle/correspondence.py +203 -0
  39. umf_access/lifecycle/generation_authority_bootstrap.py +1491 -0
  40. umf_access/lifecycle/generation_authority_session.py +125 -0
  41. umf_access/lifecycle/generation_enrollment_authority.py +1108 -0
  42. umf_access/lifecycle/generation_enrollment_ledger.py +698 -0
  43. umf_access/lifecycle/generation_ingress.py +185 -0
  44. umf_access/lifecycle/generation_root_registry.py +138 -0
  45. umf_access/lifecycle/head.py +250 -0
  46. umf_access/lifecycle/head_view.py +81 -0
  47. umf_access/lifecycle/host.py +1183 -0
  48. umf_access/lifecycle/ingress_custody.py +750 -0
  49. umf_access/lifecycle/ingress_local_postgres.py +7990 -0
  50. umf_access/lifecycle/ingress_store.py +1488 -0
  51. umf_access/lifecycle/ledger.py +276 -0
  52. umf_access/lifecycle/ledger_schema.py +116 -0
  53. umf_access/lifecycle/mixed.py +593 -0
  54. umf_access/lifecycle/outcome_schema.py +136 -0
  55. umf_access/lifecycle/owner_approval_core.py +1810 -0
  56. umf_access/lifecycle/owner_authority.py +472 -0
  57. umf_access/lifecycle/owner_bootstrap.py +2077 -0
  58. umf_access/lifecycle/owner_wire.py +161 -0
  59. umf_access/lifecycle/phase_fence.py +52 -0
  60. umf_access/lifecycle/phase_policy.py +422 -0
  61. umf_access/lifecycle/privileges.py +145 -0
  62. umf_access/lifecycle/probe.py +39 -0
  63. umf_access/lifecycle/progress.py +497 -0
  64. umf_access/lifecycle/roles.py +96 -0
  65. umf_access/lifecycle/row_originals.py +1712 -0
  66. umf_access/lifecycle/row_originals_creation.py +759 -0
  67. umf_access/lifecycle/row_originals_receipt.py +413 -0
  68. umf_access/lifecycle/seeds.py +99 -0
  69. umf_access/lifecycle/sql_containment.py +358 -0
  70. umf_access/lifecycle/sql_containment_cli.py +33 -0
  71. umf_access/lifecycle/sql_containment_parser.py +20 -0
  72. umf_access/lifecycle/supervisor_journal_codec.py +1251 -0
  73. umf_access/lifecycle/table_boundary.py +22 -0
  74. umf_access/lifecycle/target_custody_codec.py +788 -0
  75. umf_access/lifecycle/witness.py +72 -0
  76. umf_access/managed_actions.py +271 -0
  77. umf_access/managed_bulk.py +353 -0
  78. umf_access/managed_delta.py +150 -0
  79. umf_access/managed_support.py +166 -0
  80. umf_access/manifest_commands.py +278 -0
  81. umf_access/native_actions.py +1007 -0
  82. umf_access/native_program.py +570 -0
  83. umf_access/pages.py +125 -0
  84. umf_access/postgres_bulk.py +509 -0
  85. umf_access/postgres_read.py +1230 -0
  86. umf_access/postgres_search.py +639 -0
  87. umf_access/protocols.py +665 -0
  88. umf_access/py.typed +0 -0
  89. umf_access/related_keys.py +233 -0
  90. umf_access/reviewed.py +706 -0
  91. umf_access/search_catalog.py +122 -0
  92. umf_access/targets.py +312 -0
  93. umf_access/types.py +220 -0
  94. umf_access/unified/__init__.py +187 -0
  95. umf_access/unified/_binding.py +654 -0
  96. umf_access/unified/head_session.py +144 -0
  97. umf_access/unified/native_binding.py +143 -0
  98. umf_access/unified/operation_values.py +173 -0
  99. umf_access/unified/outcome_values.py +76 -0
  100. umf_access/unified/session_async.py +161 -0
  101. umf_access/unified/session_binding.py +108 -0
  102. umf_access/unified/session_policy.py +152 -0
  103. umf_access/unified/session_psycopg2.py +70 -0
  104. umf_access/unified/session_sqlalchemy.py +161 -0
  105. umf_access/unified/session_sync.py +148 -0
  106. umf_access/unified/table_reads.py +314 -0
  107. umf_access/unified/table_writes.py +193 -0
  108. umf_access/unity_search.py +312 -0
  109. umf_access/values.py +280 -0
  110. umf_access/verification.py +64 -0
  111. umf_access-0.1.0.dev8.dist-info/METADATA +15 -0
  112. umf_access-0.1.0.dev8.dist-info/RECORD +117 -0
  113. umf_access-0.1.0.dev8.dist-info/WHEEL +4 -0
  114. umf_access-0.1.0.dev8.dist-info/entry_points.txt +4 -0
  115. umf_access-0.1.0.dev8.dist-info/licenses/LICENSE-APACHE +201 -0
  116. umf_access-0.1.0.dev8.dist-info/licenses/LICENSE-MIT +21 -0
  117. umf_access-0.1.0.dev8.dist-info/licenses/LICENSE.md +239 -0
@@ -0,0 +1,497 @@
1
+ # SPDX-License-Identifier: MIT OR Apache-2.0
2
+ """Fixed owner-only durable receipts for mixed migration phases."""
3
+ from __future__ import annotations
4
+
5
+ import hashlib
6
+ import json
7
+ from typing import Any
8
+ from uuid import uuid4
9
+
10
+ from .catalog import (
11
+ CatalogError,
12
+ _all,
13
+ _columns,
14
+ _constraint_shapes,
15
+ _execute,
16
+ _index_shapes,
17
+ _one,
18
+ _q,
19
+ )
20
+
21
+ PROGRESS = 'umf_lifecycle_progress'
22
+ _DEFINITIONS = [
23
+ '"migration_id" pg_catalog.text COLLATE pg_catalog."C" NOT NULL',
24
+ '"plan_digest" pg_catalog.text COLLATE pg_catalog."C" NOT NULL',
25
+ '"expected_head" pg_catalog.text COLLATE pg_catalog."C"',
26
+ '"file_digest" pg_catalog.text COLLATE pg_catalog."C"',
27
+ '"phase_index" pg_catalog.int8 NOT NULL',
28
+ '"state" pg_catalog.text COLLATE pg_catalog."C" NOT NULL',
29
+ '"phase_digest" pg_catalog.text COLLATE pg_catalog."C" NOT NULL',
30
+ '"completed_steps" pg_catalog.jsonb NOT NULL',
31
+ '"prefix_witness" pg_catalog.jsonb',
32
+ ]
33
+ _CONSTRAINTS = [
34
+ ('umf_lifecycle_progress_pkey', 'PRIMARY KEY ("migration_id")'),
35
+ ('progress_positive_phase', 'CHECK ("phase_index">=0)'),
36
+ ('progress_plan_digest', 'CHECK ("plan_digest" ~ \'^[a-f0-9]{64}$\')'),
37
+ ('progress_head_digest', 'CHECK ("expected_head" IS NULL OR "expected_head" ~ \'^[a-f0-9]{64}$\')'),
38
+ ('progress_file_digest', 'CHECK ("file_digest" IS NULL OR "file_digest" ~ \'^[a-f0-9]{64}$\')'),
39
+ ('progress_state', 'CHECK ("state" IN (\'ready\',\'intent\',\'complete\'))'),
40
+ ('progress_phase_digest', 'CHECK ("phase_digest" ~ \'^[a-f0-9]{64}$\')'),
41
+ ('progress_step_array', 'CHECK (pg_catalog.jsonb_typeof("completed_steps")=\'array\')'),
42
+ ('progress_witness_object', 'CHECK ("prefix_witness" IS NULL OR pg_catalog.jsonb_typeof("prefix_witness")=\'object\')'),
43
+ ]
44
+ _STATE = """SELECT c.relkind,c.relpersistence,r.rolname,c.relrowsecurity,c.relforcerowsecurity,
45
+ c.relispartition,c.relhassubclass,c.relhasrules,c.relreplident,
46
+ EXISTS(SELECT FROM pg_catalog.pg_trigger t WHERE t.tgrelid=c.oid AND NOT t.tgisinternal),
47
+ EXISTS(SELECT FROM pg_catalog.pg_inherits i WHERE i.inhrelid=c.oid),
48
+ EXISTS(SELECT FROM pg_catalog.pg_policy p WHERE p.polrelid=c.oid),r.oid,c.oid,c.relam
49
+ FROM pg_catalog.pg_class c JOIN pg_catalog.pg_namespace n ON n.oid=c.relnamespace
50
+ JOIN pg_catalog.pg_roles r ON r.oid=c.relowner WHERE n.nspname=%s AND c.relname=%s"""
51
+
52
+
53
+ def _canonical_bytes(value: Any) -> bytes:
54
+ """Bounded JSON subset used for phase receipt hashes."""
55
+ return json.dumps(value, ensure_ascii=False, sort_keys=True, separators=(',', ':'), allow_nan=False).encode('utf-8')
56
+
57
+
58
+ def _phase_digest(phase: dict[str, Any], steps: list[dict[str, Any]]) -> str:
59
+ return hashlib.sha256(_canonical_bytes({'phase': phase, 'steps': steps})).hexdigest()
60
+
61
+
62
+ def _verified_phases(plan: dict[str, Any]) -> list[dict[str, Any]]:
63
+ """Check exact ordered step coverage before consulting or creating progress."""
64
+ profile = plan.get('executionProfile')
65
+ phases = plan.get('phases')
66
+ options_version = plan.get('options', {}).get('version')
67
+ if options_version == 'umf.table-migration-options/0.2':
68
+ expected_profile = {'version': 'umf.table-migration-execution/0.1',
69
+ 'progressRelation': PROGRESS, 'ownerOnly': True}
70
+ allow_backfill_tighten = False
71
+ elif options_version == 'umf.table-migration-options/0.3':
72
+ from .approval import APPROVAL_PROFILE
73
+
74
+ expected_profile = {'version': 'umf.table-migration-execution/0.2',
75
+ 'progressRelation': PROGRESS, 'ownerOnly': True}
76
+ if plan.get('approvalProfile') != APPROVAL_PROFILE:
77
+ raise CatalogError('approval-profile-mismatch')
78
+ allow_backfill_tighten = True
79
+ elif options_version == 'umf.table-migration-options/0.4':
80
+ from .approval import APPROVAL_PROFILE
81
+
82
+ expected_profile = {'version': 'umf.table-migration-execution/0.3',
83
+ 'progressRelation': PROGRESS, 'ownerOnly': True}
84
+ if (plan.get('version') != 'umf.table-migration/0.4'
85
+ or plan.get('approvalProfile') != APPROVAL_PROFILE):
86
+ raise CatalogError('approval-profile-mismatch')
87
+ allow_backfill_tighten = True
88
+ elif options_version == 'umf.table-migration-options/0.5':
89
+ from .approval import APPROVAL_PROFILE
90
+
91
+ expected_profile = {'version': 'umf.table-migration-execution/0.4',
92
+ 'progressRelation': PROGRESS, 'ownerOnly': True}
93
+ if (plan.get('version') != 'umf.table-migration/0.5'
94
+ or plan.get('approvalProfile') != APPROVAL_PROFILE):
95
+ raise CatalogError('approval-profile-mismatch')
96
+ allow_backfill_tighten = False
97
+ elif options_version == 'umf.table-migration-options/0.6':
98
+ from .approval import APPROVAL_PROFILE
99
+
100
+ expected_profile = {'version': 'umf.table-migration-execution/0.5',
101
+ 'progressRelation': PROGRESS, 'ownerOnly': True,
102
+ 'ingressProfile': 'umf.table-generation-ingress/0.1'}
103
+ if (plan.get('version') != 'umf.table-migration/0.6'
104
+ or plan.get('approvalProfile') != APPROVAL_PROFILE):
105
+ raise CatalogError('approval-profile-mismatch')
106
+ allow_backfill_tighten = False
107
+ else:
108
+ raise CatalogError('mixed-phase-profile')
109
+ if (profile != expected_profile
110
+ or type(phases) is not list or type(plan.get('steps')) is not list):
111
+ raise CatalogError('mixed-phase-profile')
112
+ if not phases:
113
+ # A v0.3 source-only plan can have no native operations (for example,
114
+ # an added typed command). It publishes through the host's atomic
115
+ # no-effect finalizer and must not create a progress relation.
116
+ if options_version in ('umf.table-migration-options/0.3','umf.table-migration-options/0.4') and not plan['steps']:
117
+ return phases
118
+ raise CatalogError('mixed-phase-profile')
119
+ by_id = {step.get('id'): step for step in plan['steps'] if type(step) is dict}
120
+ if len(by_id) != len(plan['steps']):
121
+ raise CatalogError('mixed-phase-profile')
122
+ seen: list[str] = []
123
+ for index, phase in enumerate(phases, 1):
124
+ if (type(phase) is not dict or set(phase) != {'id','kind','transaction','steps'}
125
+ or phase['id'] != 'phase-'+str(index).zfill(5)
126
+ or phase['kind'] not in ('transaction','backfill','concurrent-index','constraint-add','constraint-validation','seed','backfill-tighten','backfill-add','default-change','field-replacement')
127
+ or phase['transaction'] not in ('required','forbidden')
128
+ or type(phase['steps']) is not list or not phase['steps']):
129
+ raise CatalogError('mixed-phase-profile')
130
+ selected = []
131
+ for step_id in phase['steps']:
132
+ step = by_id.get(step_id)
133
+ if step is None or step['transaction'] != phase['transaction']:
134
+ raise CatalogError('mixed-phase-profile')
135
+ selected.append(step)
136
+ seen.append(step_id)
137
+ if options_version == 'umf.table-migration-options/0.6':
138
+ _verify_field_replacement_phase(plan, phase, selected)
139
+ if phase['kind'] != 'field-replacement':
140
+ raise CatalogError('mixed-phase-profile')
141
+ continue
142
+ expected_kind = []
143
+ append_group = any(step.get('phaseOperation') == 'add-column' for step in selected)
144
+ if options_version == 'umf.table-migration-options/0.5':
145
+ options = plan.get('options')
146
+ markers = options.get('reviewedChanges') if type(options) is dict else None
147
+ if (len(phases) != 1 or len(plan['steps']) != 1 or len(selected) != 1
148
+ or phase['kind'] != 'default-change' or phase['transaction'] != 'required'
149
+ or type(options) is not dict or options.get('version') != options_version
150
+ or options.get('backfills') != [] or options.get('concurrentIndexes') != []
151
+ or options.get('validations') != [] or type(markers) is not list or len(markers) != 1):
152
+ raise CatalogError('mixed-phase-profile')
153
+ marker, step = markers[0], selected[0]
154
+ target = step.get('phaseTarget')
155
+ expected_path = marker.get('path') if type(marker) is dict and type(marker.get('path')) is str else None
156
+ target_columns = []
157
+ next_columns = plan.get('next', {}).get('expectedCatalog', {}).get('columns', [])
158
+ if type(expected_path) is str and expected_path.endswith('/default') and type(next_columns) is list:
159
+ column_path = expected_path[:-len('/default')]
160
+ target_columns = [column for column in next_columns
161
+ if type(column) is dict
162
+ and column.get('sourcePath') == column_path
163
+ and column.get('table') == (target.get('table') if type(target) is dict else None)
164
+ and column.get('field') == (target.get('field') if type(target) is dict else None)]
165
+ if (type(marker) is not dict or marker.get('kind') != 'change-default'
166
+ or type(expected_path) is not str or not expected_path.endswith('/default')
167
+ or len(target_columns) != 1
168
+ or step.get('kind') != 'table' or step.get('transaction') != 'required'
169
+ or step.get('phaseOperation') != 'change-default'
170
+ or step.get('operation') not in ('set-default', 'drop-default')
171
+ or type(step.get('sql')) is not str or not step['sql']
172
+ or step.get('sourcePath') != expected_path
173
+ or type(target) is not dict or set(target) != {'table', 'field'}
174
+ or type(target.get('table')) is not str or not target['table']
175
+ or type(target.get('field')) is not dict
176
+ or set(target['field']) != {'module', 'element'}
177
+ or any(type(target['field'].get(key)) is not str or not target['field'][key]
178
+ for key in ('module', 'element'))):
179
+ raise CatalogError('mixed-phase-profile')
180
+ expected_kind.append('default-change')
181
+ else:
182
+ for step in selected:
183
+ if append_group and step.get('phaseOperation') in ('add-column','target-check','backfill','install-default','tighten-not-null'):
184
+ expected_kind.append('backfill-add')
185
+ elif step.get('phaseOperation') in ('backfill','tighten-not-null'):
186
+ expected_kind.append('backfill-tighten')
187
+ elif step.get('phaseOperation') in ('add-column','target-check','install-default'):
188
+ expected_kind.append('backfill-add')
189
+ elif step['kind'] == 'backfill':
190
+ expected_kind.append('backfill')
191
+ elif step['kind'] == 'index' and step['transaction'] == 'forbidden':
192
+ expected_kind.append('concurrent-index')
193
+ elif step.get('operation') == 'add-not-valid':
194
+ expected_kind.append('constraint-add')
195
+ elif step.get('operation') == 'validate':
196
+ expected_kind.append('constraint-validation')
197
+ elif step.get('kind') == 'seed':
198
+ expected_kind.append('seed')
199
+ else:
200
+ expected_kind.append('transaction')
201
+ if ((len(set(expected_kind)) != 1 or expected_kind[0] != phase['kind']
202
+ or phase['kind'] not in ('transaction','backfill-add') and len(selected) != 1)
203
+ and (phase['kind'] not in ('backfill-tighten','backfill-add') or not allow_backfill_tighten)):
204
+ raise CatalogError('mixed-phase-profile')
205
+ if phase['kind'] == 'backfill-tighten':
206
+ if not allow_backfill_tighten or len(selected) != 2:
207
+ raise CatalogError('mixed-phase-profile')
208
+ backfill, tighten = selected
209
+ target = backfill.get('phaseTarget')
210
+ if (phase['transaction'] != 'required'
211
+ or backfill.get('phaseOperation') != 'backfill'
212
+ or backfill.get('kind') != 'backfill'
213
+ or backfill.get('transaction') != 'required'
214
+ or type(backfill.get('operation')) is not str
215
+ or not backfill['operation']
216
+ or tighten.get('phaseOperation') != 'tighten-not-null'
217
+ or tighten.get('transaction') != 'required'
218
+ or type(tighten.get('sql')) is not str
219
+ or not tighten['sql']
220
+ or type(target) is not dict
221
+ or set(target) != {'table','field'}
222
+ or type(target.get('table')) is not str
223
+ or not target['table']
224
+ or type(target.get('field')) is not dict
225
+ or set(target['field']) != {'module','element'}
226
+ or any(type(target['field'][key]) is not str or not target['field'][key]
227
+ for key in ('module','element'))
228
+ or tighten.get('phaseTarget') != target):
229
+ raise CatalogError('mixed-phase-profile')
230
+ if phase['kind'] == 'backfill-add':
231
+ roles = [step.get('phaseOperation') for step in selected]
232
+ backfill_index = roles.index('backfill') if 'backfill' in roles else -1
233
+ default_index = roles.index('install-default') if 'install-default' in roles else -1
234
+ targets = [step.get('phaseTarget') for step in selected]
235
+ if (options_version != 'umf.table-migration-options/0.4'
236
+ or len(selected) < 3 or roles[0] != 'add-column'
237
+ or roles[-1] != 'tighten-not-null'
238
+ or roles.count('backfill') != 1 or roles.count('tighten-not-null') != 1
239
+ or roles.count('install-default') > 1 or backfill_index < 1
240
+ or any(role != 'target-check' for role in roles[1:backfill_index])
241
+ or default_index != -1 and default_index < backfill_index
242
+ or any(role != 'install-default' for role in roles[backfill_index+1:-1])
243
+ or any(step['transaction'] != 'required' for step in selected)
244
+ or any(target != targets[0] for target in targets)
245
+ or selected[0].get('kind') != 'table'
246
+ or selected[backfill_index].get('kind') != 'backfill'
247
+ or selected[backfill_index].get('sql') != ''
248
+ or selected[-1].get('kind') != 'table'):
249
+ raise CatalogError('mixed-phase-profile')
250
+ if phase['kind'] == 'backfill' and (len(selected) != 1 or selected[0]['kind'] != 'backfill'):
251
+ raise CatalogError('mixed-phase-profile')
252
+ if phase['kind'] == 'concurrent-index' and (len(selected) != 1 or selected[0]['kind'] != 'index' or selected[0]['transaction'] != 'forbidden'):
253
+ raise CatalogError('mixed-phase-profile')
254
+ if phase['kind'] == 'constraint-add' and (len(selected) != 1 or selected[0].get('operation') != 'add-not-valid'):
255
+ raise CatalogError('mixed-phase-profile')
256
+ if phase['kind'] == 'constraint-validation' and (len(selected) != 1 or selected[0].get('operation') != 'validate'):
257
+ raise CatalogError('mixed-phase-profile')
258
+ if phase['kind'] == 'seed' and (len(selected) != 1 or selected[0].get('kind') != 'seed'):
259
+ raise CatalogError('mixed-phase-profile')
260
+ if seen != [step['id'] for step in plan['steps']]:
261
+ raise CatalogError('mixed-phase-profile')
262
+ return phases
263
+
264
+
265
+ def _verify_field_replacement_phase(plan: dict[str, Any], phase: dict[str, Any],
266
+ selected: list[dict[str, Any]]) -> None:
267
+ """Validate the closed host-facing shape for the atomic G11 phase.
268
+
269
+ Compiler verification remains authoritative for complete source/dependency
270
+ correspondence and DAG construction. This boundary independently refuses
271
+ phase or target mutations before host custody or native effects.
272
+ """
273
+ options = plan.get('options')
274
+ steps = plan.get('steps')
275
+ if (plan.get('version') != 'umf.table-migration/0.6'
276
+ or type(options) is not dict
277
+ or set(options) != {'version', 'backfills', 'concurrentIndexes',
278
+ 'reviewedChanges', 'validations'}
279
+ or options.get('version') != 'umf.table-migration-options/0.6'
280
+ or type(options.get('backfills')) is not list
281
+ or type(options.get('reviewedChanges')) is not list
282
+ or options.get('concurrentIndexes') != []
283
+ or options.get('validations') != []
284
+ or type(steps) is not list or len(steps) < 2
285
+ or len(selected) != len(steps)
286
+ or len(plan.get('phases', [])) != 1
287
+ or phase.get('kind') != 'field-replacement'
288
+ or phase.get('transaction') != 'required'
289
+ or phase.get('steps') != [step.get('id') for step in steps]
290
+ or any(step.get('transaction') != 'required' for step in steps)):
291
+ raise CatalogError('mixed-phase-profile')
292
+
293
+ column_roles = {'drop-column', 'add-column', 'target-check', 'backfill',
294
+ 'install-default', 'tighten-not-null'}
295
+ dependency_roles = {'dependency-drop', 'dependency-add'}
296
+ previous = plan.get('previous')
297
+ next_bundle = plan.get('next')
298
+ if type(previous) is not dict or type(next_bundle) is not dict:
299
+ raise CatalogError('mixed-phase-profile')
300
+ previous_columns = previous.get('expectedCatalog', {}).get('columns')
301
+ next_columns = next_bundle.get('expectedCatalog', {}).get('columns')
302
+ if type(previous_columns) is not list or type(next_columns) is not list:
303
+ raise CatalogError('mixed-phase-profile')
304
+
305
+ drops: set[tuple[str, str, str]] = set()
306
+ adds: set[tuple[str, str, str]] = set()
307
+ seen_backfills: set[tuple[str, str, str]] = set()
308
+ for step in selected:
309
+ role = step.get('phaseOperation')
310
+ if role not in column_roles | dependency_roles:
311
+ raise CatalogError('mixed-phase-profile')
312
+ target = step.get('phaseTarget')
313
+ dependency = step.get('phaseDependency')
314
+ if role in column_roles:
315
+ if (type(target) is not dict or set(target) != {'table', 'field'}
316
+ or type(target.get('table')) is not str or not target['table']
317
+ or type(target.get('field')) is not dict
318
+ or set(target['field']) != {'module', 'element'}
319
+ or any(type(target['field'].get(key)) is not str
320
+ or not target['field'][key]
321
+ for key in ('module', 'element'))
322
+ or 'phaseDependency' in step):
323
+ raise CatalogError('mixed-phase-profile')
324
+ identity = (target['table'], target['field']['module'],
325
+ target['field']['element'])
326
+ old_matches = [column for column in previous_columns
327
+ if column.get('table') == identity[0]
328
+ and column.get('field') == {'module': identity[1],
329
+ 'element': identity[2]}]
330
+ new_matches = [column for column in next_columns
331
+ if column.get('table') == identity[0]
332
+ and column.get('field') == {'module': identity[1],
333
+ 'element': identity[2]}]
334
+ if role == 'drop-column':
335
+ if (step.get('kind') != 'table' or len(old_matches) != 1
336
+ or new_matches or step.get('sourcePath') != old_matches[0].get('sourcePath')
337
+ or type(step.get('sql')) is not str or not step['sql']):
338
+ raise CatalogError('mixed-phase-profile')
339
+ if identity in drops or 'operation' in step:
340
+ raise CatalogError('mixed-phase-profile')
341
+ drops.add(identity)
342
+ elif role == 'add-column':
343
+ if (step.get('kind') != 'table' or old_matches or len(new_matches) != 1
344
+ or step.get('sourcePath') != new_matches[0].get('sourcePath')
345
+ or type(step.get('sql')) is not str or not step['sql']
346
+ or identity in adds):
347
+ raise CatalogError('mixed-phase-profile')
348
+ adds.add(identity)
349
+ else:
350
+ if len(new_matches) != 1 or old_matches:
351
+ raise CatalogError('mixed-phase-profile')
352
+ expected_path = new_matches[0].get('sourcePath')
353
+ if role == 'backfill':
354
+ if (step.get('kind') != 'backfill' or step.get('sql') != ''
355
+ or type(step.get('operation')) is not str or not step['operation']):
356
+ raise CatalogError('mixed-phase-profile')
357
+ selected_backfills = [(index, item) for index, item in enumerate(options['backfills'])
358
+ if type(item) is dict and item.get('table') == identity[0]
359
+ and item.get('column') == {'module': identity[1],
360
+ 'element': identity[2]}
361
+ and item.get('operation') == step['operation']
362
+ and item.get('scopedRows') is True]
363
+ if (len(selected_backfills) != 1 or identity in seen_backfills
364
+ or step.get('sourcePath') != '/options/backfills/'
365
+ + str(selected_backfills[0][0])):
366
+ raise CatalogError('mixed-phase-profile')
367
+ seen_backfills.add(identity)
368
+ else:
369
+ if (step.get('kind') != 'table'
370
+ or type(step.get('sql')) is not str or not step['sql']):
371
+ raise CatalogError('mixed-phase-profile')
372
+ if (type(step.get('sourcePath')) is not str
373
+ or not step['sourcePath']):
374
+ raise CatalogError('mixed-phase-profile')
375
+ if (role in ('install-default', 'tighten-not-null')
376
+ and step.get('sourcePath') != expected_path):
377
+ raise CatalogError('mixed-phase-profile')
378
+ elif role in dependency_roles:
379
+ if ('phaseTarget' in step or type(dependency) is not dict
380
+ or set(dependency) != {'table', 'kind', 'id', 'sourcePath', 'meaningDigest'}
381
+ or type(dependency.get('table')) is not str or not dependency['table']
382
+ or dependency.get('kind') not in ('check', 'foreignKey', 'index',
383
+ 'key', 'policy', 'grant')
384
+ or type(dependency.get('id')) is not str or not dependency['id']
385
+ or type(dependency.get('sourcePath')) is not str
386
+ or not dependency['sourcePath']
387
+ or type(dependency.get('meaningDigest')) is not str
388
+ or len(dependency['meaningDigest']) != 64
389
+ or any(char not in '0123456789abcdef'
390
+ for char in dependency['meaningDigest'])
391
+ or step.get('sourcePath') != dependency['sourcePath']
392
+ or step.get('transaction') != 'required'
393
+ or step.get('sql') is None):
394
+ raise CatalogError('mixed-phase-profile')
395
+ if (step.get('kind') not in {'table', 'constraint', 'foreignKey',
396
+ 'index', 'policy', 'grant'}
397
+ or type(step.get('sql')) is not str or not step['sql']):
398
+ raise CatalogError('mixed-phase-profile')
399
+ if (type(dependency['sourcePath']) is not str
400
+ or not dependency['sourcePath']):
401
+ raise CatalogError('mixed-phase-profile')
402
+ else:
403
+ raise CatalogError('mixed-phase-profile')
404
+
405
+ if (not drops or not adds or len(seen_backfills) != len(options['backfills'])
406
+ or sum(1 for step in selected if step.get('phaseOperation') == 'drop-column') != len(drops)
407
+ or sum(1 for step in selected if step.get('phaseOperation') == 'add-column') != len(adds)):
408
+ raise CatalogError('mixed-phase-profile')
409
+
410
+
411
+ def _create_progress(connection: Any, schema: str, name: str = PROGRESS) -> dict[str, str]:
412
+ definitions = list(_DEFINITIONS)
413
+ aliases: dict[str, str] = {}
414
+ for constraint, body in _CONSTRAINTS:
415
+ actual = constraint if name == PROGRESS else 'umf_verify_'+uuid4().hex
416
+ aliases[actual] = constraint
417
+ definitions.append('CONSTRAINT '+_q(actual)+' '+body)
418
+ _execute(connection, 'CREATE TABLE '+_q(schema)+'.'+_q(name)+' ('+', '.join(definitions)+') USING heap')
419
+ return aliases
420
+
421
+
422
+ def _verify_progress_schema(connection: Any, source: dict[str, Any], *, create: bool = False) -> bool:
423
+ """Exact schema, owner, heap, constraints, indexes and default ACL check."""
424
+ schema, owner = source['configuration']['schema'], source['configuration']['ownerRole']
425
+ state = _one(connection, _STATE, (schema, PROGRESS))
426
+ if state is None:
427
+ if not create:
428
+ return False
429
+ _create_progress(connection, schema)
430
+ state = _one(connection, _STATE, (schema, PROGRESS))
431
+ if tuple(state[:12]) != ('r','p',owner,False,False,False,False,False,'d',False,False,False):
432
+ # Relhasrules and relreplident are checked separately below; keep the
433
+ # expected tuple explicit to reject views, partitions, RLS and triggers.
434
+ raise CatalogError('progress-catalog-mismatch')
435
+ owner_id, relation_id = state[12:14]
436
+ if state[14] != _one(connection, "SELECT oid FROM pg_catalog.pg_am WHERE amname='heap'")[0]:
437
+ raise CatalogError('progress-catalog-mismatch')
438
+ _execute(connection, 'LOCK TABLE '+_q(schema)+'.'+_q(PROGRESS)+' IN ACCESS EXCLUSIVE MODE')
439
+ if _one(connection, _STATE, (schema, PROGRESS)) != state:
440
+ raise CatalogError('progress-catalog-mismatch')
441
+ actual_acl = _all(connection, """SELECT x.grantor,x.grantee,x.privilege_type,x.is_grantable
442
+ FROM pg_catalog.pg_class c,LATERAL pg_catalog.aclexplode(COALESCE(c.relacl,pg_catalog.acldefault('r',c.relowner))) x
443
+ WHERE c.oid=%s ORDER BY 1,2,3,4""", (relation_id,))
444
+ expected_acl = _all(connection, """SELECT grantor,grantee,privilege_type,is_grantable
445
+ FROM pg_catalog.aclexplode(pg_catalog.acldefault('r',%s::pg_catalog.oid)) ORDER BY 1,2,3,4""", (owner_id,))
446
+ if actual_acl != expected_acl or _one(connection, """SELECT count(*) FROM pg_catalog.pg_attribute a,
447
+ LATERAL pg_catalog.aclexplode(a.attacl) x WHERE a.attrelid=%s""", (relation_id,)) != (0,):
448
+ raise CatalogError('progress-privilege-mismatch')
449
+ temporary = 'umf_verify_'+uuid4().hex
450
+ aliases = _create_progress(connection, schema, temporary)
451
+ if (_columns(connection, schema, PROGRESS) != _columns(connection, schema, temporary)
452
+ or _constraint_shapes(connection, schema, PROGRESS, {}) != _constraint_shapes(connection, schema, temporary, aliases)
453
+ or _index_shapes(connection, schema, PROGRESS, {}) != _index_shapes(connection, schema, temporary, aliases)):
454
+ _execute(connection, 'DROP TABLE '+_q(schema)+'.'+_q(temporary))
455
+ raise CatalogError('progress-catalog-mismatch')
456
+ _execute(connection, 'DROP TABLE '+_q(schema)+'.'+_q(temporary))
457
+ return True
458
+
459
+
460
+ def _progress_rows(connection: Any, schema: str) -> list[dict[str, Any]]:
461
+ rows = _all(connection, 'SELECT migration_id,plan_digest,expected_head,file_digest,phase_index,state,phase_digest,completed_steps,prefix_witness FROM '+_q(schema)+'.'+_q(PROGRESS)+' ORDER BY migration_id', ())
462
+ if len(rows) > 1:
463
+ raise CatalogError('progress-capacity')
464
+ result = []
465
+ for row in rows:
466
+ migration_id, plan_digest, expected_head, file_digest, phase_index, state, phase_digest, steps, witness = row
467
+ if type(steps) is not list or witness is not None and type(witness) is not dict:
468
+ raise CatalogError('progress-state-mismatch')
469
+ result.append({'migrationId': migration_id, 'planDigest': plan_digest,
470
+ 'expectedHead': expected_head, 'fileDigest': file_digest,
471
+ 'phaseIndex': phase_index, 'state': state,
472
+ 'phaseDigest': phase_digest, 'completedSteps': steps,
473
+ 'prefixWitness': witness})
474
+ return result
475
+
476
+
477
+ def _write_progress(connection: Any, schema: str, receipt: dict[str, Any]) -> None:
478
+ """Upsert is only called inside the same transaction as its required phase."""
479
+ payload = json.dumps(receipt['completedSteps'], separators=(',', ':'))
480
+ witness = None if receipt['prefixWitness'] is None else json.dumps(receipt['prefixWitness'], separators=(',', ':'))
481
+ _execute(connection, 'INSERT INTO '+_q(schema)+'.'+_q(PROGRESS)+' (migration_id,plan_digest,expected_head,file_digest,phase_index,state,phase_digest,completed_steps,prefix_witness) VALUES (%s,%s,%s,%s,%s,%s,%s,%s::pg_catalog.jsonb,%s::pg_catalog.jsonb) ON CONFLICT (migration_id) DO UPDATE SET phase_index=EXCLUDED.phase_index,state=EXCLUDED.state,phase_digest=EXCLUDED.phase_digest,completed_steps=EXCLUDED.completed_steps,prefix_witness=EXCLUDED.prefix_witness',
482
+ (receipt['migrationId'], receipt['planDigest'], receipt['expectedHead'], receipt['fileDigest'], receipt['phaseIndex'], receipt['state'], receipt['phaseDigest'], payload, witness))
483
+
484
+
485
+ def _assert_progress_binding(receipt: dict[str, Any], *, migration_id: str, plan_digest: str,
486
+ expected_head: str | None, file_digest: str | None) -> None:
487
+ if (receipt['migrationId'] != migration_id or receipt['planDigest'] != plan_digest
488
+ or receipt['expectedHead'] != expected_head or receipt['fileDigest'] != file_digest):
489
+ raise CatalogError('progress-binding-mismatch')
490
+
491
+
492
+ def _delete_progress(connection: Any, schema: str, migration_id: str) -> None:
493
+ _execute(connection, 'DELETE FROM '+_q(schema)+'.'+_q(PROGRESS)+' WHERE migration_id=%s', (migration_id,))
494
+
495
+
496
+ def _drop_progress(connection: Any, schema: str) -> None:
497
+ _execute(connection, 'DROP TABLE '+_q(schema)+'.'+_q(PROGRESS))
@@ -0,0 +1,96 @@
1
+ # SPDX-License-Identifier: MIT OR Apache-2.0
2
+ """Native role reachability for explicitly selected person identities.
3
+
4
+ This administrative check does not infer people from all role memberships:
5
+ trusted pool issuers can intentionally issue both person and batch sessions.
6
+ ACL containment and runtime admission remain separate requirements.
7
+ """
8
+ from __future__ import annotations
9
+
10
+ from typing import Any
11
+
12
+ from .catalog import CatalogError, _installation
13
+ from .probe import _Query, _run
14
+
15
+ _CLOSURE = """WITH switched AS MATERIALIZED (
16
+ SELECT oid FROM pg_catalog.pg_roles WHERE pg_catalog.pg_has_role(%s::pg_catalog.oid,oid,'SET'))
17
+ SELECT r.oid,r.rolname,r.rolsuper,r.rolbypassrls,r.rolcreatedb,r.rolcreaterole,r.rolreplication
18
+ FROM pg_catalog.pg_roles r WHERE EXISTS (
19
+ SELECT FROM switched s WHERE pg_catalog.pg_has_role(s.oid,r.oid,'USAGE'))"""
20
+
21
+
22
+ def verify_native_role_scope(connection: Any, bundle: dict[str, object], *,
23
+ person_roles: tuple[str, ...],
24
+ statement_timeout_ms: int = 30_000,
25
+ lock_timeout_ms: int = 5_000) -> dict[str, object]:
26
+ """Verify exact selected people and configured role boundaries, without ACL admission.
27
+
28
+ The trusted host must supply its actual person registry, excluding its pool
29
+ issuer. Each selected person must inherit the person audience as that person;
30
+ SET-only membership cannot substitute an umbrella identity for them. Checks
31
+ include SET reachability followed by inherited privileges, not MEMBER alone.
32
+ The caller owns the install transaction; no commit or role mutation occurs.
33
+ """
34
+ if (type(person_roles) is not tuple or len(person_roles) > 1024
35
+ or any(type(role) is not str or not role or '\0' in role
36
+ or len(role.encode('utf-8')) > 63 for role in person_roles)
37
+ or len(set(person_roles)) != len(person_roles)):
38
+ raise ValueError("an exact tuple of at most 1024 distinct person roles is required")
39
+ with _installation(connection, bundle, statement_timeout_ms=statement_timeout_ms,
40
+ lock_timeout_ms=lock_timeout_ms) as source:
41
+ _run(connection,_role_scope_steps(source,person_roles))
42
+ return {"bundleDigest": source["bundleDigest"], "roleScopeVerified": True,
43
+ "verifiedPersonRoles": list(person_roles), "lifecycleAdmission": False}
44
+
45
+
46
+ def _role_scope_steps(source, person_roles, batch_roles=()):
47
+ cfg = source['configuration']
48
+ owner, person, batch = (cfg[key] for key in ('ownerRole', 'personRole', 'batchRole'))
49
+ groups = list(cfg['groupRoles'].values())
50
+ configured = [owner, person, batch, *groups]
51
+ if set(configured).intersection(person_roles):
52
+ raise CatalogError('person-identity-required')
53
+ if set(batch_roles).intersection(set(configured)-{batch}) or set(batch_roles).intersection(person_roles):
54
+ raise CatalogError('batch-identity-required')
55
+ selected = sorted(set(configured)|set(person_roles)|set(batch_roles))
56
+ identities: dict[str, int] = {}
57
+ login = {}
58
+ for name in selected:
59
+ row = (yield _Query('one', 'SELECT oid,rolcanlogin FROM pg_catalog.pg_roles WHERE rolname=%s', (name,)))
60
+ if row is None or (name in configured and row[1]):
61
+ raise CatalogError('role-scope-mismatch')
62
+ identities[name] = row[0]
63
+ login[name] = row[1]
64
+ facts = []
65
+ for name in selected:
66
+ effective = (yield _Query('all', _CLOSURE, (identities[name],)))
67
+ if len(effective) > 4096:
68
+ raise CatalogError('role-scope-capacity')
69
+ if not effective or any(any(row[2:]) or row[1].startswith('pg_') for row in effective):
70
+ raise CatalogError('role-scope-mismatch')
71
+ administrators = (yield _Query('one', 'SELECT EXISTS (SELECT FROM pg_catalog.pg_auth_members WHERE member=ANY(%s::pg_catalog.oid[]) AND admin_option)', ([row[0] for row in effective],)))
72
+ if administrators != (False,):
73
+ raise CatalogError('role-scope-mismatch')
74
+ for row in effective:
75
+ if (yield _Query('one', "SELECT pg_catalog.has_parameter_privilege(%s::pg_catalog.oid,'session_replication_role','SET')", (row[0],))) != (False,):
76
+ raise CatalogError('role-scope-mismatch')
77
+ reached = {row[1] for row in effective}
78
+ forbidden = {owner, person} if name == batch or name in batch_roles else {owner, batch}
79
+ if name == owner:
80
+ if reached != {owner}:
81
+ raise CatalogError('role-scope-mismatch')
82
+ elif reached.intersection(forbidden):
83
+ raise CatalogError('role-scope-mismatch')
84
+ if name in person_roles:
85
+ inherits = (yield _Query('one', "SELECT pg_catalog.pg_has_role(%s::pg_catalog.oid,%s::pg_catalog.oid,'USAGE')", (identities[name], identities[person])))
86
+ if inherits != (True,):
87
+ raise CatalogError('person-identity-required')
88
+ if name in batch_roles:
89
+ inherits = (yield _Query('one', "SELECT pg_catalog.pg_has_role(%s::pg_catalog.oid,%s::pg_catalog.oid,'USAGE')", (identities[name],identities[batch])))
90
+ if inherits != (True,):
91
+ raise CatalogError('batch-identity-required')
92
+ members = yield _Query('all',"SELECT oid,rolname FROM pg_catalog.pg_roles WHERE pg_catalog.pg_has_role(%s::pg_catalog.oid,oid,'MEMBER') ORDER BY oid LIMIT 4097",(identities[name],))
93
+ if len(members)>4096:
94
+ raise CatalogError('role-scope-capacity')
95
+ facts.append([name,identities[name],login[name],sorted(effective,key=lambda row:row[0]),members])
96
+ return {'identities':identities,'facts':facts}