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,1712 @@
1
+ # SPDX-License-Identifier: MIT OR Apache-2.0
2
+ """Fixed PostgreSQL row-originals store and issued-instance guard.
3
+
4
+ This is a deliberately finite G04 provider. It is not an archive API and does
5
+ not accept author SQL, caller-selected native types, or caller-created custody
6
+ objects. The native supervisor/owner-approval adapter is loaded lazily so an
7
+ unintegrated adapter fails closed instead of falling back to structural trust.
8
+ """
9
+ from __future__ import annotations
10
+
11
+ import hashlib
12
+ import json
13
+ import re
14
+ import uuid
15
+ from typing import Any
16
+
17
+ from .catalog import CatalogError, _all, _execute, _one, _q
18
+
19
+ STORE_PROFILE = 'umf.native-row-originals-store/0.1'
20
+ IDENTITY_PROFILE = 'umf.native-row-identity/0.1'
21
+ ROW_RECORD_PROFILE = 'umf.native-row-identity/0.1'
22
+ ARCHIVE_RECORD_PROFILE = 'umf.native-row-originals/0.1'
23
+ AUTHORITY_PROFILE = 'umf.pg18.original-store-authority-evidence/0.1'
24
+ _RECOVERY_PROVIDER_SEAL = object()
25
+ _HEX = re.compile(r'^[a-f0-9]{64}$')
26
+ _MAX_RECORD_BYTES = 1_048_576
27
+ _MAX_TABLES = 4096
28
+ _MAX_ARCHIVES = 4096
29
+ _MAX_ISSUED = 1_000_000
30
+ _MAX_LOGICAL_BYTES = 1_073_741_824
31
+
32
+ _ROW_TABLE_DDL = '''CREATE TABLE {schema}."row_tables" (
33
+ "table_token" pg_catalog.uuid PRIMARY KEY,
34
+ "installation_id" pg_catalog.text COLLATE pg_catalog."C" NOT NULL CHECK ("installation_id" <> ''),
35
+ "business_table_oid" pg_catalog.oid NOT NULL UNIQUE,
36
+ "business_schema_oid" pg_catalog.oid NOT NULL,
37
+ "table_binding" pg_catalog.text COLLATE pg_catalog."C" NOT NULL,
38
+ "issued_count" pg_catalog.int8 NOT NULL CHECK ("issued_count" BETWEEN 0 AND 1000000),
39
+ "record" pg_catalog.jsonb NOT NULL CHECK (pg_catalog.jsonb_typeof("record") = 'object'),
40
+ "record_digest" pg_catalog.text COLLATE pg_catalog."C" NOT NULL CHECK ("record_digest" ~ '^[a-f0-9]{{64}}$')
41
+ ) USING heap'''
42
+ _ARCHIVES_DDL = '''CREATE TABLE {schema}."archives" (
43
+ "archive_id" pg_catalog.uuid PRIMARY KEY,
44
+ "table_token" pg_catalog.uuid NOT NULL REFERENCES {schema}."row_tables"("table_token") ON UPDATE RESTRICT ON DELETE RESTRICT,
45
+ "state" pg_catalog.text COLLATE pg_catalog."C" NOT NULL CHECK ("state" IN ('capturing','complete')),
46
+ "values_relation_oid" pg_catalog.oid NOT NULL UNIQUE,
47
+ "row_count" pg_catalog.int8 NOT NULL CHECK ("row_count" BETWEEN 0 AND 1000000),
48
+ "logical_bytes" pg_catalog.int8 NOT NULL CHECK ("logical_bytes" BETWEEN 0 AND 1073741824),
49
+ "record" pg_catalog.jsonb NOT NULL CHECK (pg_catalog.jsonb_typeof("record") = 'object'),
50
+ "record_digest" pg_catalog.text COLLATE pg_catalog."C" NOT NULL CHECK ("record_digest" ~ '^[a-f0-9]{{64}}$')
51
+ ) USING heap'''
52
+ _ISSUED_DDL = '''CREATE TABLE {schema}."issued_instances" (
53
+ "table_token" pg_catalog.uuid NOT NULL REFERENCES {schema}."row_tables"("table_token") ON UPDATE RESTRICT ON DELETE RESTRICT,
54
+ "instance_id" pg_catalog.uuid NOT NULL,
55
+ PRIMARY KEY ("table_token", "instance_id")
56
+ ) USING heap'''
57
+
58
+ _ROW_RECORD_KEYS = {
59
+ 'profile', 'providerId', 'installationId', 'targetCustody', 'tableToken',
60
+ 'tableBinding', 'businessRelation', 'idColumn', 'revisionColumn',
61
+ 'uniqueConstraint', 'revisionConstraint', 'trigger', 'function',
62
+ 'creationReservationDigest', 'maxIssuedInstances',
63
+ }
64
+ _ARCHIVE_RECORD_KEYS = {
65
+ 'profile', 'providerId', 'installationId', 'targetCustody', 'archiveId',
66
+ 'tableToken', 'field', 'sourceDigest', 'targetDigest', 'planDigest',
67
+ 'approvalDigest', 'policy', 'sourceNativeDomain', 'valuesRelation',
68
+ 'creationReservationDigest', 'state', 'rowCount', 'logicalBytes',
69
+ }
70
+
71
+
72
+ def _fail(reason: str) -> None:
73
+ raise CatalogError(reason)
74
+
75
+
76
+ def _exact_object(value: Any, keys: set[str], reason: str = 'row-originals-record-invalid') -> dict[str, Any]:
77
+ if type(value) is not dict or set(value) != keys:
78
+ _fail(reason)
79
+ return value
80
+
81
+
82
+ def _uuid(value: Any) -> str:
83
+ if type(value) is not str:
84
+ _fail('row-originals-record-invalid')
85
+ try:
86
+ parsed = uuid.UUID(value)
87
+ except (ValueError, AttributeError):
88
+ _fail('row-originals-record-invalid')
89
+ if str(parsed) != value:
90
+ _fail('row-originals-record-invalid')
91
+ return value
92
+
93
+
94
+ def _digest(value: Any) -> str:
95
+ if type(value) is not str or _HEX.fullmatch(value) is None:
96
+ _fail('row-originals-record-invalid')
97
+ return value
98
+
99
+
100
+ def _safe_int(value: Any, low: int, high: int) -> int:
101
+ if type(value) is not int or not low <= value <= high:
102
+ _fail('row-originals-record-invalid')
103
+ return value
104
+
105
+
106
+ def _canonical_bytes(value: Any) -> bytes:
107
+ # Bound depth/node count before JSON encoding; reject Python-only values,
108
+ # non-finite floats, non-ASCII keys and non-UTF8 strings.
109
+ stack: list[tuple[Any, int]] = [(value, 0)]
110
+ nodes = 0
111
+ while stack:
112
+ item, depth = stack.pop()
113
+ nodes += 1
114
+ if nodes > 100_000 or depth > 64:
115
+ _fail('row-originals-record-capacity')
116
+ if item is None or type(item) is bool:
117
+ continue
118
+ if type(item) is int:
119
+ if abs(item) > 9_007_199_254_740_991:
120
+ _fail('row-originals-record-invalid')
121
+ continue
122
+ if type(item) is float:
123
+ _fail('row-originals-record-invalid')
124
+ if type(item) is str:
125
+ try:
126
+ item.encode('utf-8')
127
+ except UnicodeEncodeError:
128
+ _fail('row-originals-record-invalid')
129
+ if '\x00' in item:
130
+ _fail('row-originals-record-invalid')
131
+ continue
132
+ if type(item) is list:
133
+ stack.extend((child, depth + 1) for child in item)
134
+ continue
135
+ if type(item) is dict:
136
+ for key, child in item.items():
137
+ if type(key) is not str or not key.isascii():
138
+ _fail('row-originals-record-invalid')
139
+ stack.append((key, depth + 1))
140
+ stack.append((child, depth + 1))
141
+ continue
142
+ _fail('row-originals-record-invalid')
143
+ try:
144
+ result = json.dumps(value, ensure_ascii=False, sort_keys=True,
145
+ separators=(',', ':'), allow_nan=False).encode('utf-8')
146
+ except (TypeError, ValueError, UnicodeError, RecursionError):
147
+ _fail('row-originals-record-invalid')
148
+ if len(result) > _MAX_RECORD_BYTES:
149
+ _fail('row-originals-record-capacity')
150
+ return result
151
+
152
+
153
+ def record_digest(value: Any) -> str:
154
+ return hashlib.sha256(_canonical_bytes(value)).hexdigest()
155
+
156
+
157
+ def originals_schema_name(provider_id: str) -> str:
158
+ provider = _uuid(provider_id)
159
+ return 'umf_originals_' + provider.replace('-', '')
160
+
161
+
162
+ def validate_row_table_record(value: Any) -> dict[str, Any]:
163
+ record = _exact_object(value, _ROW_RECORD_KEYS)
164
+ if record['profile'] != ROW_RECORD_PROFILE:
165
+ _fail('row-originals-record-invalid')
166
+ _uuid(record['providerId']); _uuid(record['tableToken'])
167
+ if type(record['installationId']) is not str or not record['installationId']:
168
+ _fail('row-originals-record-invalid')
169
+ if (type(record['tableBinding']) is not str or not record['tableBinding']
170
+ or '\x00' in record['tableBinding']):
171
+ _fail('row-originals-record-invalid')
172
+ relation = _exact_object(record['businessRelation'],
173
+ {'schemaOid', 'schemaName', 'tableOid', 'tableName'})
174
+ _safe_int(relation['schemaOid'], 1, 2**32 - 1)
175
+ _safe_int(relation['tableOid'], 1, 2**32 - 1)
176
+ for key in ('schemaName', 'tableName'):
177
+ if type(relation[key]) is not str or not relation[key] or '\x00' in relation[key]:
178
+ _fail('row-originals-record-invalid')
179
+ for key in ('idColumn', 'revisionColumn'):
180
+ _native_column(record[key])
181
+ for key in ('uniqueConstraint', 'revisionConstraint', 'trigger', 'function'):
182
+ item = _exact_object(record[key], {'oid', 'name', 'definitionDigest'})
183
+ _safe_int(item['oid'], 1, 2**32 - 1)
184
+ if type(item['name']) is not str or not item['name'] or '\x00' in item['name']:
185
+ _fail('row-originals-record-invalid')
186
+ _digest(item['definitionDigest'])
187
+ _digest(record['creationReservationDigest'])
188
+ _safe_int(record['maxIssuedInstances'], 1, _MAX_ISSUED)
189
+ if 'targetCustody' not in record or type(record['targetCustody']) is not dict:
190
+ _fail('row-originals-record-invalid')
191
+ _canonical_bytes(record)
192
+ return record
193
+
194
+
195
+ def _native_column(value: Any) -> dict[str, Any]:
196
+ item = _exact_object(value, {'attnum', 'name', 'typeOid', 'typeMod'})
197
+ _safe_int(item['attnum'], 1, 32767)
198
+ _safe_int(item['typeOid'], 1, 2**32 - 1)
199
+ _safe_int(item['typeMod'], -1, 2**31 - 1)
200
+ if type(item['name']) is not str or not item['name'] or '\x00' in item['name']:
201
+ _fail('row-originals-record-invalid')
202
+ return item
203
+
204
+
205
+ def validate_archive_record(value: Any) -> dict[str, Any]:
206
+ record = _exact_object(value, _ARCHIVE_RECORD_KEYS)
207
+ if record['profile'] != ARCHIVE_RECORD_PROFILE or record['state'] not in ('capturing', 'complete'):
208
+ _fail('row-originals-record-invalid')
209
+ for key in ('providerId', 'archiveId', 'tableToken'):
210
+ _uuid(record[key])
211
+ if type(record['installationId']) is not str or not record['installationId']:
212
+ _fail('row-originals-record-invalid')
213
+ for key in ('sourceDigest', 'targetDigest', 'planDigest', 'approvalDigest',
214
+ 'creationReservationDigest'):
215
+ _digest(record[key])
216
+ _safe_int(record['rowCount'], 0, _MAX_ISSUED)
217
+ _safe_int(record['logicalBytes'], 0, _MAX_LOGICAL_BYTES)
218
+ policy = _exact_object(record['policy'], {'id', 'revision'})
219
+ field = _exact_object(record['field'], {'module', 'element'})
220
+ for item in (*policy.values(), *field.values()):
221
+ if type(item) is not str or not item or '\x00' in item:
222
+ _fail('row-originals-record-invalid')
223
+ domain = _exact_object(record['sourceNativeDomain'],
224
+ {'schema', 'name', 'typeOid', 'typeMod', 'collationOid'})
225
+ for key in ('schema', 'name'):
226
+ if type(domain[key]) is not str or not domain[key] or '\x00' in domain[key]:
227
+ _fail('row-originals-record-invalid')
228
+ _safe_int(domain['typeOid'], 1, 2**32 - 1)
229
+ _safe_int(domain['typeMod'], -1, 2**31 - 1)
230
+ _safe_int(domain['collationOid'], 0, 2**32 - 1)
231
+ values = _exact_object(record['valuesRelation'], {'schema', 'name', 'oid'})
232
+ for key in ('schema', 'name'):
233
+ if type(values[key]) is not str or not values[key] or '\x00' in values[key]:
234
+ _fail('row-originals-record-invalid')
235
+ _safe_int(values['oid'], 1, 2**32 - 1)
236
+ _canonical_bytes(record)
237
+ return record
238
+
239
+
240
+ def _authority_context(supervisor: object, evidence: object, approval: object,
241
+ custodian: object, target: object, *,
242
+ budget_reservation: object | None = None) -> dict[str, Any]:
243
+ """Resolve only the exact supervisor capability; missing G04 adapter refuses."""
244
+ try:
245
+ from .ingress_local_postgres import (
246
+ LocalPostgresSupervisor,
247
+ _VerifiedNativeStorePreparation,
248
+ )
249
+ except ImportError:
250
+ _fail('row-originals-authority-unavailable')
251
+ if (type(supervisor) is not LocalPostgresSupervisor
252
+ or type(evidence) is not _VerifiedNativeStorePreparation
253
+ or evidence.supervisor is not supervisor
254
+ or evidence.custodian is not custodian
255
+ or evidence.target_handle is not target):
256
+ _fail('row-originals-authority-required')
257
+ try:
258
+ from .generation_ingress import TargetCustody
259
+ from .ingress_custody import LocalTargetCustodian
260
+ if type(custodian) is not LocalTargetCustodian or type(target) is not TargetCustody:
261
+ _fail('row-originals-authority-required')
262
+ verified_target = custodian._resolve_target_custody(target)
263
+ target_reference = custodian._public_reference(target)
264
+ if evidence.verified_target is not verified_target:
265
+ _fail('row-originals-authority-invalid')
266
+ except CatalogError:
267
+ raise
268
+ except Exception: # noqa: BLE001 -- native custody failures are sanitized at this boundary
269
+ _fail('row-originals-authority-invalid')
270
+ try:
271
+ verified = supervisor._resolve_original_store_preparation(
272
+ evidence, approval, custodian=custodian, target=target,
273
+ budget_reservation=budget_reservation)
274
+ except TypeError:
275
+ # An earlier adapter signature cannot silently authorize the G04 store.
276
+ _fail('row-originals-authority-unavailable')
277
+ except Exception: # noqa: BLE001 -- resolver diagnostics never leave the trust boundary
278
+ _fail('row-originals-authority-invalid')
279
+ required_verified = {
280
+ 'profile', 'payload', 'store', 'verifiedTarget', 'approval', 'nativeObservation',
281
+ }
282
+ if (type(verified) is not dict or set(verified) != required_verified
283
+ or verified.get('profile') != AUTHORITY_PROFILE):
284
+ _fail('row-originals-authority-invalid')
285
+ payload = verified.get('payload')
286
+ payload_fields = {
287
+ 'profile', 'supervisorId', 'custodianId', 'providerId', 'installationId',
288
+ 'ownerAuthorityId', 'ownerPolicyRevision', 'registrationDigest',
289
+ 'targetCustodyDigest', 'authorityPreparationReceiptDigest', 'maintenance',
290
+ 'controller', 'businessOwner', 'requiredMemberships', 'requiredSettings',
291
+ 'nativeAuthorityObservationDigest',
292
+ }
293
+ if (type(payload) is not dict or set(payload) != payload_fields
294
+ or payload.get('profile') != AUTHORITY_PROFILE
295
+ or verified['verifiedTarget'] is not verified_target
296
+ or verified['approval'] is not approval):
297
+ _fail('row-originals-authority-invalid')
298
+ if (payload['custodianId'] != custodian.custodian_id
299
+ or payload['providerId'] != supervisor._provider_id
300
+ or payload['installationId'] != supervisor._bound_installation_id
301
+ or payload['targetCustodyDigest'] != _digest_json(target_reference)):
302
+ _fail('row-originals-authority-invalid')
303
+ from .owner_authority import _validate_native_store_intent
304
+ try:
305
+ _validate_native_store_intent(payload, supervisor._owner_authority.authority_id,
306
+ supervisor._owner_authority.policy_revision)
307
+ except Exception: # noqa: BLE001 -- native observation text is not exposed
308
+ _fail('row-originals-authority-invalid')
309
+ observation = verified['nativeObservation']
310
+ if (type(observation) is not dict
311
+ or _digest_json(observation) != payload['nativeAuthorityObservationDigest']
312
+ or observation.get('profile') != 'umf.pg18.native-session-authority-observation/0.1'
313
+ or observation.get('registrationDigest') != payload['registrationDigest']
314
+ or observation.get('targetCustodyDigest') != payload['targetCustodyDigest']):
315
+ _fail('row-originals-authority-invalid')
316
+ store = verified.get('store')
317
+ expected_store = {
318
+ 'profile': STORE_PROFILE,
319
+ 'storeId': payload.get('providerId'),
320
+ 'schemaName': originals_schema_name(payload.get('providerId')),
321
+ }
322
+ if store != expected_store:
323
+ _fail('row-originals-authority-invalid')
324
+ return {**verified, 'targetCustody': target_reference}
325
+
326
+
327
+ def _digest_json(value: Any) -> str:
328
+ return hashlib.sha256(_canonical_bytes(value)).hexdigest()
329
+
330
+
331
+ def _create_store_schema(connection: Any, schema: str, controller: str) -> int:
332
+ existing = _one(connection,
333
+ 'SELECT oid FROM pg_catalog.pg_namespace WHERE nspname=%s', (schema,))
334
+ if existing is not None:
335
+ _fail('row-originals-store-conflict')
336
+ _execute(connection, 'CREATE SCHEMA ' + _q(schema) + ' AUTHORIZATION ' + _q(controller))
337
+ for ddl in (_ROW_TABLE_DDL, _ARCHIVES_DDL, _ISSUED_DDL):
338
+ _execute(connection, ddl.format(schema=_q(schema)))
339
+ row = _one(connection, 'SELECT oid FROM pg_catalog.pg_namespace WHERE nspname=%s', (schema,))
340
+ if row is None:
341
+ _fail('row-originals-store-create-unobserved')
342
+ return int(row[0])
343
+
344
+
345
+ def identity_function_sql(schema: str, function_name: str, *, token: str,
346
+ table_oid: int, table_schema: str, table_name: str,
347
+ id_column: str, revision_column: str) -> str:
348
+ """Render the one fixed guard; all identifiers are validated then quoted."""
349
+ token = _uuid(token)
350
+ _safe_int(table_oid, 1, 2**32 - 1)
351
+ for value in (schema, function_name, table_schema, table_name, id_column, revision_column):
352
+ if type(value) is not str or not value or '\x00' in value:
353
+ _fail('row-originals-record-invalid')
354
+ qschema, qfunction = _q(schema), _q(function_name)
355
+ qid, qrev = _q(id_column), _q(revision_column)
356
+ literal_schema = "'" + table_schema.replace("'", "''") + "'"
357
+ literal_table = "'" + table_name.replace("'", "''") + "'"
358
+ literal_token = "'" + token + "'::pg_catalog.uuid"
359
+ qualified_tables = qschema + '."row_tables"'
360
+ qualified_ledger = qschema + '."issued_instances"'
361
+ return f'''CREATE FUNCTION {qschema}.{qfunction}() RETURNS trigger
362
+ LANGUAGE plpgsql VOLATILE CALLED ON NULL INPUT SECURITY DEFINER
363
+ PARALLEL UNSAFE COST 100 SET search_path = pg_catalog AS $umf_identity$
364
+ DECLARE reservation_count pg_catalog.int8;
365
+ BEGIN
366
+ IF TG_RELID <> {table_oid}::pg_catalog.oid OR TG_TABLE_SCHEMA <> {literal_schema}
367
+ OR TG_TABLE_NAME <> {literal_table} THEN
368
+ RAISE EXCEPTION USING ERRCODE = '42501', MESSAGE = 'umf row identity target denied';
369
+ END IF;
370
+ IF TG_OP = 'INSERT' THEN
371
+ UPDATE {qualified_tables} SET "issued_count" = "issued_count" OPERATOR(pg_catalog.+) 1
372
+ WHERE "table_token" = {literal_token} AND "business_table_oid" = TG_RELID
373
+ AND "issued_count" < ("record"->>'maxIssuedInstances')::pg_catalog.int8;
374
+ GET DIAGNOSTICS reservation_count = ROW_COUNT;
375
+ IF reservation_count <> 1 THEN
376
+ RAISE EXCEPTION USING ERRCODE = '54000', MESSAGE = 'umf row identity capacity exhausted';
377
+ END IF;
378
+ NEW.{qid} := pg_catalog.gen_random_uuid();
379
+ NEW.{qrev} := 1::pg_catalog.int8;
380
+ INSERT INTO {qualified_ledger} ("table_token", "instance_id")
381
+ VALUES ({literal_token}, NEW.{qid});
382
+ ELSIF TG_OP = 'UPDATE' THEN
383
+ IF NEW.{qid} IS DISTINCT FROM OLD.{qid} OR NEW.{qrev} IS DISTINCT FROM OLD.{qrev} THEN
384
+ RAISE EXCEPTION USING ERRCODE = '42501', MESSAGE = 'umf row identity mutation denied';
385
+ END IF;
386
+ IF OLD.{qrev} = 9223372036854775807 THEN
387
+ RAISE EXCEPTION USING ERRCODE = '22003', MESSAGE = 'umf row revision exhausted';
388
+ END IF;
389
+ NEW.{qid} := OLD.{qid};
390
+ NEW.{qrev} := OLD.{qrev} OPERATOR(pg_catalog.+) 1::pg_catalog.int8;
391
+ ELSE
392
+ RAISE EXCEPTION USING ERRCODE = '42501', MESSAGE = 'umf row identity event denied';
393
+ END IF;
394
+ RETURN NEW;
395
+ END;
396
+ $umf_identity$'''
397
+
398
+
399
+ _HANDLE_SEAL = object()
400
+
401
+
402
+ class EnrolledTable:
403
+ """Opaque provider handle for one object-bound enrolled table."""
404
+
405
+ __slots__ = (
406
+ '_id_column', '_issuer', '_max_issued_instances', '_relation_oid',
407
+ '_revision_column', '_schema_name', '_table_name', '_table_token',
408
+ )
409
+
410
+ def __init__(self, seal: object, issuer: object, *, table_token: str,
411
+ relation_oid: int, schema_name: str, table_name: str,
412
+ id_column: str, revision_column: str, max_issued_instances: int):
413
+ if seal is not _HANDLE_SEAL:
414
+ raise TypeError('row table handles are provider-issued')
415
+ self._issuer = issuer
416
+ self._table_token = table_token
417
+ self._relation_oid = relation_oid
418
+ self._schema_name = schema_name
419
+ self._table_name = table_name
420
+ self._id_column = id_column
421
+ self._revision_column = revision_column
422
+ self._max_issued_instances = max_issued_instances
423
+
424
+ def __setattr__(self, name: str, value: object) -> None:
425
+ if hasattr(self, name):
426
+ raise AttributeError('row table handles are immutable')
427
+ object.__setattr__(self, name, value)
428
+
429
+ def __reduce_ex__(self, _protocol: int):
430
+ raise TypeError('row table handles cannot be serialized')
431
+
432
+ def __repr__(self) -> str:
433
+ return '<EnrolledTable opaque>'
434
+
435
+
436
+ class OriginalArchive:
437
+ """Opaque provider handle; original values and archive records stay private."""
438
+
439
+ __slots__ = ('_archive_id', '_issuer', '_table_token')
440
+
441
+ def __init__(self, seal: object, issuer: object, archive_id: str, table_token: str):
442
+ if seal is not _HANDLE_SEAL:
443
+ raise TypeError('archive handles are provider-issued')
444
+ self._issuer = issuer
445
+ self._archive_id = archive_id
446
+ self._table_token = table_token
447
+
448
+ def __setattr__(self, name: str, value: object) -> None:
449
+ if hasattr(self, name):
450
+ raise AttributeError('archive handles are immutable')
451
+ object.__setattr__(self, name, value)
452
+
453
+ def __reduce_ex__(self, _protocol: int):
454
+ raise TypeError('archive handles cannot be serialized')
455
+
456
+ def __repr__(self) -> str:
457
+ return '<OriginalArchive opaque>'
458
+
459
+
460
+ def _reservation_receipt_fields(record_bytes: bytes, record: dict[str, Any],
461
+ target_reference: dict[str, Any]) -> dict[str, Any]:
462
+ """Derive the public receipt links from the exact original reservation."""
463
+ from .row_originals_receipt import canonical_bytes
464
+
465
+ return {
466
+ 'providerId': record['providerId'],
467
+ 'installationId': record['installationId'],
468
+ 'storeId': record['providerId'],
469
+ 'reservationDigest': hashlib.sha256(record_bytes).hexdigest(),
470
+ 'creationRequestDigest': record['creationRequestDigest'],
471
+ 'creationApprovalDigest': record['creationApprovalDigest'],
472
+ 'targetCustodyDigest': hashlib.sha256(canonical_bytes(target_reference)).hexdigest(),
473
+ }
474
+
475
+
476
+ def reserve_originals_store_creation(supervisor: object, evidence: object,
477
+ approval: object, custodian: object,
478
+ target: object, store: dict[str, Any],
479
+ connection: Any,
480
+ *, creation_budget: object | None = None,
481
+ ) -> tuple[object, dict[str, Any]]:
482
+ """Resolve the exact supervisor-issued original reservation before DDL."""
483
+ from .row_originals_receipt import (
484
+ _RESERVATION_KEYS,
485
+ _RESERVATION_PROFILE,
486
+ MAX_RECEIPT_BYTES,
487
+ _digest,
488
+ _fail,
489
+ _no_duplicates,
490
+ _safe_int,
491
+ _uuid,
492
+ canonical_bytes,
493
+ )
494
+ try:
495
+ from .ingress_local_postgres import LocalPostgresSupervisor
496
+ except ImportError:
497
+ _fail('row-originals-creation-reservation-unavailable')
498
+ if type(supervisor) is not LocalPostgresSupervisor:
499
+ _fail('row-originals-creation-reservation-invalid')
500
+ if type(store) is not dict:
501
+ _fail('row-originals-creation-reservation-invalid')
502
+ try:
503
+ from .generation_ingress import TargetCustody
504
+ from .ingress_custody import LocalTargetCustodian
505
+ except ImportError:
506
+ _fail('row-originals-creation-reservation-unavailable')
507
+ if type(custodian) is not LocalTargetCustodian or type(target) is not TargetCustody:
508
+ _fail('row-originals-creation-reservation-invalid')
509
+ expected_store = {
510
+ 'profile': 'umf.native-row-originals-store/0.1',
511
+ 'storeId': store.get('storeId'),
512
+ 'schemaName': store.get('schemaName'),
513
+ }
514
+ if set(store) != {'profile', 'storeId', 'schemaName'} or store != expected_store:
515
+ _fail('row-originals-creation-reservation-invalid')
516
+ try:
517
+ reservation = supervisor.reserve_originals_store_creation(
518
+ evidence, approval, custodian=custodian, target=target, store=store,
519
+ connection=connection, creation_budget=creation_budget)
520
+ verified = supervisor._resolve_originals_store_creation_reservation(
521
+ reservation, evidence=evidence, approval=approval,
522
+ custodian=custodian, target=target, store=store,
523
+ budget_reservation=reservation)
524
+ except CatalogError:
525
+ raise
526
+ except Exception: # noqa: BLE001 -- authority implementation details stay private
527
+ _fail('row-originals-creation-reservation-invalid')
528
+ if verified is not reservation:
529
+ _fail('row-originals-creation-reservation-invalid')
530
+ record_bytes = getattr(reservation, 'record_bytes', None)
531
+ if type(record_bytes) is not bytes:
532
+ _fail('row-originals-creation-reservation-invalid')
533
+ try:
534
+ record = json.loads(record_bytes, object_pairs_hook=_no_duplicates)
535
+ except (json.JSONDecodeError, UnicodeDecodeError, CatalogError, RecursionError):
536
+ _fail('row-originals-creation-reservation-invalid')
537
+ if (canonical_bytes(record) != record_bytes or type(record) is not dict
538
+ or set(record) != _RESERVATION_KEYS
539
+ or record['profile'] != _RESERVATION_PROFILE):
540
+ _fail('row-originals-creation-reservation-invalid')
541
+ _uuid(record['reservationId'])
542
+ provider_id = _uuid(record['providerId'])
543
+ if record['providerId'] != store.get('storeId'):
544
+ _fail('row-originals-creation-reservation-invalid')
545
+ installation_id = record['installationId']
546
+ try:
547
+ installation_size = len(installation_id.encode('utf-8')) if type(installation_id) is str else MAX_RECEIPT_BYTES + 1
548
+ except UnicodeEncodeError:
549
+ _fail('row-originals-creation-reservation-invalid')
550
+ if (type(installation_id) is not str or not installation_id or '\x00' in installation_id
551
+ or installation_size > 256):
552
+ _fail('row-originals-creation-reservation-invalid')
553
+ if (provider_id != supervisor._provider_id
554
+ or installation_id != supervisor._bound_installation_id):
555
+ _fail('row-originals-creation-reservation-invalid')
556
+ _digest(record['creationRequestDigest'])
557
+ _digest(record['creationApprovalDigest'])
558
+ _digest(record['nativeAuthorityEvidenceDigest'])
559
+ _digest(record['configurationDigest'])
560
+ _safe_int(record['custodySequence'], 1, 2**53 - 1)
561
+ target_reference = custodian._public_reference(target)
562
+ if record['targetCustody'] != target_reference:
563
+ _fail('row-originals-creation-reservation-invalid')
564
+ if record['store'] != store:
565
+ _fail('row-originals-creation-reservation-invalid')
566
+ try:
567
+ if (approval.intent_digest != record['creationRequestDigest']
568
+ or approval.approval_digest != record['creationApprovalDigest']):
569
+ _fail('row-originals-creation-reservation-invalid')
570
+ except AttributeError:
571
+ _fail('row-originals-creation-reservation-invalid')
572
+ receipt_fields = _reservation_receipt_fields(record_bytes, record, target_reference)
573
+ return reservation, receipt_fields
574
+
575
+ class PgRowOriginalsStore:
576
+ """Private same-database store for typed original values and row identity.
577
+
578
+ All public methods require an active transaction and a freshly resolved
579
+ supervisor-issued G04 store authority. No purge method exists in .1.
580
+ """
581
+
582
+ __slots__ = (
583
+ '_approval', '_archives', '_authority', '_connection', '_controller_oid',
584
+ '_controller_role', '_creation_attempt', '_creation_capability',
585
+ '_creation_receipt', '_creation_receipt_fields', '_creation_reservation',
586
+ '_custodian', '_evidence', '_installation_id', '_issuer',
587
+ '_provider_id', '_recovery_only', '_schema', '_schema_oid',
588
+ '_supervisor', '_tables', '_target',
589
+ )
590
+
591
+ def __init__(self, connection: Any, *, supervisor: object, evidence: object,
592
+ approval: object, custodian: object, target: object,
593
+ provider_id: str, installation_id: str, controller_role: str,
594
+ controller_oid: int):
595
+ self._authority = _authority_context(supervisor, evidence, approval, custodian, target)
596
+ self._connection = connection
597
+ self._supervisor = supervisor
598
+ self._evidence = evidence
599
+ self._approval = approval
600
+ self._custodian = custodian
601
+ self._target = target
602
+ self._provider_id = _uuid(provider_id)
603
+ self._installation_id = installation_id
604
+ self._controller_role = controller_role
605
+ self._controller_oid = _safe_int(controller_oid, 1, 2**32 - 1)
606
+ self._schema = originals_schema_name(provider_id)
607
+ self._schema_oid: int | None = None
608
+ self._creation_reservation: object | None = None
609
+ self._creation_attempt: object | None = None
610
+ self._creation_receipt_fields: dict[str, Any] | None = None
611
+ self._creation_receipt: dict[str, Any] | None = None
612
+ self._creation_capability: object | None = None
613
+ self._issuer = object()
614
+ self._tables: dict[int, tuple[EnrolledTable, dict[str, Any]]] = {}
615
+ self._archives: dict[int, tuple[OriginalArchive, dict[str, Any]]] = {}
616
+ self._recovery_only = False
617
+ payload = self._authority['payload']
618
+ if (payload.get('providerId') != self._provider_id
619
+ or payload.get('installationId') != installation_id
620
+ or payload.get('controller', {}).get('name') != controller_role
621
+ or payload.get('controller', {}).get('oid') != controller_oid):
622
+ _fail('row-originals-authority-invalid')
623
+
624
+ def _refresh_authority(self, *, budget: object | None = None) -> None:
625
+ if self._recovery_only:
626
+ if (self._creation_reservation is None
627
+ or self._creation_capability is None):
628
+ _fail('row-originals-store-recovery-required')
629
+ try:
630
+ with self._supervisor._original_control_lease(operation_kind='store'):
631
+ self._authority = (
632
+ self._supervisor._resolve_recovered_original_store_current_authority(
633
+ self._creation_reservation, self._creation_capability,
634
+ self._connection))
635
+ except CatalogError:
636
+ raise
637
+ except Exception: # noqa: BLE001 -- fresh current authority is required
638
+ _fail('row-originals-store-recovery-authority-invalid')
639
+ payload = self._authority['payload']
640
+ self._controller_role = payload['controller']['name']
641
+ self._controller_oid = payload['controller']['oid']
642
+ return
643
+ self._authority = _authority_context(
644
+ self._supervisor, self._evidence, self._approval, self._custodian,
645
+ self._target, budget_reservation=budget)
646
+
647
+ @classmethod
648
+ def _from_recovery(cls, seal: object, *, supervisor: object,
649
+ connection: Any, provider_id: str, installation_id: str,
650
+ controller_role: str, custodian: object, target: object):
651
+ """Construct the supervisor's restricted recovery-only provider."""
652
+ if seal is not _RECOVERY_PROVIDER_SEAL:
653
+ _fail('row-originals-store-recovery-invalid')
654
+ instance = object.__new__(cls)
655
+ instance._approval = None
656
+ instance._archives = {}
657
+ instance._authority = None
658
+ instance._connection = connection
659
+ instance._controller_oid = 0
660
+ instance._controller_role = controller_role
661
+ instance._creation_capability = None
662
+ instance._creation_receipt = None
663
+ instance._creation_attempt = None
664
+ instance._creation_receipt_fields = None
665
+ instance._creation_reservation = None
666
+ instance._custodian = custodian
667
+ instance._evidence = None
668
+ instance._installation_id = installation_id
669
+ instance._issuer = object()
670
+ instance._provider_id = _uuid(provider_id)
671
+ instance._schema = originals_schema_name(provider_id)
672
+ instance._schema_oid = None
673
+ instance._supervisor = supervisor
674
+ instance._tables = {}
675
+ instance._target = target
676
+ instance._recovery_only = True
677
+ return instance
678
+
679
+ def _require_tx(self) -> None:
680
+ # A transaction may be active before PostgreSQL assigns an XID (e.g.
681
+ # during catalog-only preparation). Asking for an assigned XID would
682
+ # both reject that valid state and conflate transaction state with XID
683
+ # allocation.
684
+ if int(self._connection.info.transaction_status) != 2:
685
+ _fail('row-originals-transaction-required')
686
+
687
+ def create(self) -> int:
688
+ if self._recovery_only:
689
+ _fail('row-originals-store-recovery-only')
690
+ self._require_tx()
691
+ if self._schema_oid is not None or self._creation_reservation is not None:
692
+ _fail('row-originals-store-already-created')
693
+ from .row_originals_creation import observe_and_write_receipt
694
+ store = {'profile': STORE_PROFILE, 'storeId': self._provider_id,
695
+ 'schemaName': self._schema}
696
+ budget = self._supervisor._mint_original_store_creation_budget(
697
+ evidence=self._evidence, approval=self._approval,
698
+ custodian=self._custodian, target=self._target,
699
+ connection=self._connection, store=store)
700
+ self._supervisor._capture_original_store_timeout_lower_bounds(
701
+ self._connection, budget)
702
+ self._refresh_authority(budget=budget)
703
+ self._verify_controller_session(budget=budget)
704
+ reservation, receipt_fields = reserve_originals_store_creation(
705
+ self._supervisor, self._evidence, self._approval, self._custodian,
706
+ self._target, store, self._connection, creation_budget=budget)
707
+ self._creation_reservation = reservation
708
+ self._creation_receipt_fields = receipt_fields
709
+ bounded = self._supervisor._budgeted_original_store_connection(reservation)
710
+ try:
711
+ self._creation_attempt = (
712
+ self._supervisor.begin_originals_store_creation_attempt(reservation))
713
+ self._schema_oid = _create_store_schema(
714
+ bounded, self._schema, self._controller_role)
715
+ bounded.execute('REVOKE ALL ON SCHEMA ' + _q(self._schema) + ' FROM PUBLIC')
716
+ self._creation_receipt = observe_and_write_receipt(
717
+ bounded, self._schema, self._schema_oid,
718
+ self._controller_oid, receipt_fields)
719
+ self._verify_store(connection=bounded)
720
+ self._supervisor._require_original_store_budget(reservation)
721
+ return self._schema_oid
722
+ finally:
723
+ bounded.restore_caller_timeouts()
724
+
725
+ def resume_creation(self) -> int:
726
+ """Resume the same pending creation only after its live abort witness settles."""
727
+ if self._recovery_only:
728
+ _fail('row-originals-store-recovery-only')
729
+ self._require_tx()
730
+ reservation = self._creation_reservation
731
+ receipt_fields = self._creation_receipt_fields
732
+ if (reservation is None or self._creation_attempt is None
733
+ or receipt_fields is None
734
+ or self._creation_capability is not None):
735
+ _fail('row-originals-creation-resume-required')
736
+ budget = reservation._budget
737
+ self._supervisor._require_original_store_budget(reservation)
738
+ self._refresh_authority(budget=budget)
739
+ self._verify_controller_session(budget=budget)
740
+ bounded = self._supervisor._budgeted_original_store_connection(
741
+ reservation)
742
+ try:
743
+ try:
744
+ from .ingress_local_postgres import LocalPostgresSupervisor
745
+ if type(self._supervisor) is not LocalPostgresSupervisor:
746
+ _fail('row-originals-creation-resume-invalid')
747
+ attempt = self._supervisor.resume_originals_store_creation_attempt(
748
+ reservation, self._creation_attempt)
749
+ except CatalogError:
750
+ raise
751
+ except Exception: # noqa: BLE001 -- retain the original authority fence
752
+ _fail('row-originals-creation-resume-invalid')
753
+ self._creation_attempt = attempt
754
+ # A positive native aborted status proves the prior transaction's
755
+ # partial catalogue/receipt values were rolled back. Discard only the
756
+ # in-memory values produced by that transaction before fixed replay.
757
+ self._schema_oid = None
758
+ self._creation_receipt = None
759
+ self._schema_oid = _create_store_schema(
760
+ bounded, self._schema, self._controller_role)
761
+ bounded.execute('REVOKE ALL ON SCHEMA ' + _q(self._schema) + ' FROM PUBLIC')
762
+ from .row_originals_creation import observe_and_write_receipt
763
+ self._creation_receipt = observe_and_write_receipt(
764
+ bounded, self._schema, self._schema_oid,
765
+ self._controller_oid, receipt_fields)
766
+ self._verify_store(connection=bounded)
767
+ self._supervisor._require_original_store_budget(reservation)
768
+ return self._schema_oid
769
+ finally:
770
+ bounded.restore_caller_timeouts()
771
+
772
+ def confirm_creation(self) -> object:
773
+ """Confirm only the original reservation after its DDL transaction committed."""
774
+ if self._recovery_only:
775
+ _fail('row-originals-store-recovery-only')
776
+ self._refresh_authority()
777
+ if (self._creation_reservation is None or self._creation_receipt is None
778
+ or int(self._connection.info.transaction_status) != 0):
779
+ _fail('row-originals-creation-confirmation-required')
780
+ try:
781
+ from .ingress_local_postgres import LocalPostgresSupervisor
782
+ if type(self._supervisor) is not LocalPostgresSupervisor:
783
+ _fail('row-originals-creation-confirmation-invalid')
784
+ capability = self._supervisor.confirm_originals_store_creation(
785
+ self._creation_reservation, receipt=self._creation_receipt)
786
+ resolved = self._supervisor._resolve_original_store_capability(
787
+ capability, original_reservation=self._creation_reservation)
788
+ except CatalogError:
789
+ raise
790
+ except Exception: # noqa: BLE001 -- do not expose native confirmation details
791
+ _fail('row-originals-creation-confirmation-invalid')
792
+ if resolved is not capability:
793
+ _fail('row-originals-creation-confirmation-invalid')
794
+ self._creation_capability = capability
795
+ return capability
796
+
797
+ def recover_creation(self) -> int:
798
+ """Reattach only a previously committed original store; never issue DDL."""
799
+ if not self._recovery_only:
800
+ self._refresh_authority()
801
+ if self._creation_reservation is not None or self._creation_capability is not None:
802
+ _fail('row-originals-store-recovery-already-attached')
803
+ try:
804
+ from .ingress_local_postgres import LocalPostgresSupervisor
805
+ if type(self._supervisor) is not LocalPostgresSupervisor:
806
+ _fail('row-originals-store-recovery-invalid')
807
+ with self._supervisor._original_control_lease(operation_kind='store'):
808
+ reservation, capability, receipt = (
809
+ self._supervisor.recover_originals_store_creation(
810
+ self._target, self._connection,
811
+ store={'profile': STORE_PROFILE, 'storeId': self._provider_id,
812
+ 'schemaName': self._schema}))
813
+ resolved = self._supervisor._resolve_original_store_capability(
814
+ capability, original_reservation=reservation)
815
+ if self._recovery_only:
816
+ self._evidence = reservation._evidence
817
+ self._approval = reservation._approval
818
+ self._custodian = reservation._custodian
819
+ self._target = reservation._target
820
+ self._authority = (
821
+ self._supervisor._resolve_recovered_original_store_current_authority(
822
+ reservation, capability, self._connection))
823
+ self._controller_role = self._authority['payload']['controller']['name']
824
+ self._controller_oid = self._authority['payload']['controller']['oid']
825
+ except CatalogError:
826
+ raise
827
+ except Exception: # noqa: BLE001 -- keep recovery authority failures private
828
+ _fail('row-originals-store-recovery-invalid')
829
+ if resolved is not capability or type(receipt) is not dict:
830
+ _fail('row-originals-store-recovery-invalid')
831
+ self._creation_reservation = reservation
832
+ self._creation_capability = capability
833
+ self._creation_receipt = receipt
834
+ self._schema_oid = receipt['schemaOid']
835
+ return self._schema_oid
836
+
837
+ def verify(self) -> None:
838
+ self._refresh_authority()
839
+ self._require_tx()
840
+ self._verify_controller_session()
841
+ self._require_creation_capability()
842
+ self._verify_store()
843
+
844
+ def _require_creation_capability(self) -> None:
845
+ if self._creation_capability is None or self._creation_reservation is None:
846
+ _fail('row-originals-creation-confirmation-required')
847
+ try:
848
+ resolved = self._supervisor._resolve_original_store_capability(
849
+ self._creation_capability,
850
+ original_reservation=self._creation_reservation)
851
+ except Exception: # noqa: BLE001 -- capability resolution is an authority boundary
852
+ _fail('row-originals-creation-confirmation-invalid')
853
+ if resolved is not self._creation_capability:
854
+ _fail('row-originals-creation-confirmation-invalid')
855
+
856
+ def _verify_controller_session(self, *, budget: object | None = None) -> None:
857
+ observation = self._authority.get('nativeObservation')
858
+ if type(observation) is not dict:
859
+ _fail('row-originals-authority-invalid')
860
+ query = '''SELECT current_user,
861
+ (SELECT oid FROM pg_catalog.pg_roles WHERE rolname=current_user),session_user,
862
+ pg_catalog.current_setting('role'),pg_catalog.current_setting('search_path'),
863
+ pg_catalog.current_setting('TimeZone'),pg_catalog.current_setting('row_security'),
864
+ pg_catalog.current_setting('session_replication_role'),
865
+ pg_catalog.current_setting('server_encoding'),
866
+ pg_catalog.current_setting('transaction_read_only'),
867
+ pg_catalog.current_setting('transaction_isolation'),
868
+ pg_catalog.current_setting('server_version_num')::pg_catalog.int4,
869
+ (SELECT system_identifier::pg_catalog.text FROM pg_catalog.pg_control_system())'''
870
+ if budget is None:
871
+ actual = _one(self._connection, query)
872
+ else:
873
+ try:
874
+ from .ingress_local_postgres import (
875
+ LocalPostgresError,
876
+ _execute_original_store_sql,
877
+ )
878
+ cursor = _execute_original_store_sql(
879
+ self._supervisor, budget, self._connection, query)
880
+ self._supervisor._require_original_store_budget(budget)
881
+ actual = cursor.fetchone()
882
+ self._supervisor._require_original_store_budget(budget)
883
+ except (CatalogError, LocalPostgresError):
884
+ raise
885
+ except Exception: # noqa: BLE001 -- no blocking fallback for creation
886
+ _fail('row-originals-controller-session-observation-unresolved')
887
+ expected = self._authority['payload']
888
+ controller = expected['controller']
889
+ maintenance = expected['maintenance']
890
+ settings = expected['requiredSettings']
891
+ if (actual is None or actual[0] != controller['name'] or actual[1] != controller['oid']
892
+ or actual[2] != maintenance['name'] or actual[3] != controller['name']
893
+ or actual[4:11] != (settings['searchPath'], settings['timeZone'],
894
+ settings['rowSecurity'], settings['sessionReplicationRole'],
895
+ 'UTF8', settings['transactionReadOnly'],
896
+ settings['transactionIsolation'])
897
+ or actual[11] != 180006
898
+ or actual[12] != observation.get('database', {}).get('systemIdentifier')):
899
+ _fail('row-originals-controller-session-required')
900
+
901
+ def _verify_store(self, *, connection: Any | None = None) -> None:
902
+ connection = self._connection if connection is None else connection
903
+ if self._schema_oid is None:
904
+ row = _one(connection,
905
+ 'SELECT oid FROM pg_catalog.pg_namespace WHERE nspname=%s',
906
+ (self._schema,))
907
+ if row is None:
908
+ _fail('row-originals-store-unavailable')
909
+ self._schema_oid = int(row[0])
910
+ schema = _one(connection, '''SELECT n.oid,n.nspowner,r.rolname,
911
+ pg_catalog.obj_description(n.oid,'pg_namespace')
912
+ FROM pg_catalog.pg_namespace n JOIN pg_catalog.pg_roles r ON r.oid=n.nspowner
913
+ WHERE n.nspname=%s''', (self._schema,))
914
+ if schema is None or schema[:3] != (
915
+ self._schema_oid, self._controller_oid, self._controller_role):
916
+ _fail('row-originals-store-catalog-mismatch')
917
+ if self._creation_receipt is None:
918
+ _fail('row-originals-creation-receipt-unavailable')
919
+ from .row_originals_creation import verify_creation_receipt
920
+ verify_creation_receipt(connection, self._schema,
921
+ self._creation_receipt, self._controller_oid)
922
+ archive_rows = _all(connection, '''SELECT archive_id,table_token,state,
923
+ values_relation_oid,row_count,logical_bytes,record,record_digest FROM '''
924
+ + _q(self._schema) + '."archives" ORDER BY archive_id')
925
+ if len(archive_rows) > _MAX_ARCHIVES:
926
+ _fail('row-originals-archive-capacity')
927
+ values_records: list[dict[str, Any]] = []
928
+ for archive_row in archive_rows:
929
+ record = validate_archive_record(archive_row[6])
930
+ native_archive_id, native_table_token = str(archive_row[0]), str(archive_row[1])
931
+ if (record_digest(record) != archive_row[7]
932
+ or record['archiveId'] != native_archive_id
933
+ or record['tableToken'] != native_table_token
934
+ or record['providerId'] != self._provider_id
935
+ or record['installationId'] != self._installation_id
936
+ or record['state'] != archive_row[2]
937
+ or record['rowCount'] != archive_row[4]
938
+ or record['logicalBytes'] != archive_row[5]
939
+ or record['valuesRelation'].get('schema') != self._schema
940
+ or record['valuesRelation'].get('oid') != archive_row[3]
941
+ or record['valuesRelation'].get('name')
942
+ != 'values_' + native_archive_id.replace('-', '')):
943
+ _fail('row-originals-archive-corrupt')
944
+ values_records.append(record)
945
+ relations = _all(connection, '''SELECT c.relname,c.relkind,c.relpersistence,
946
+ c.relowner,c.relrowsecurity,c.relforcerowsecurity,c.relispartition,c.relhassubclass,
947
+ c.relhasrules
948
+ FROM pg_catalog.pg_class c JOIN pg_catalog.pg_namespace n ON n.oid=c.relnamespace
949
+ WHERE n.nspname=%s''', (self._schema,))
950
+ expected = {'row_tables', 'archives', 'issued_instances',
951
+ 'row_tables_pkey', 'row_tables_business_table_oid_key',
952
+ 'archives_pkey', 'archives_values_relation_oid_key',
953
+ 'issued_instances_pkey'}
954
+ for record in values_records:
955
+ name = record['valuesRelation']['name']
956
+ expected.update((name, name + '_pkey'))
957
+ actual_names = {row[0] for row in relations}
958
+ if actual_names != expected:
959
+ _fail('row-originals-store-catalog-mismatch')
960
+ if any(row[1] not in ('r', 'i') or row[2] != 'p'
961
+ or row[3] != self._controller_oid or row[4] or row[5] or row[6]
962
+ or row[7] or row[8] for row in relations):
963
+ _fail('row-originals-store-catalog-mismatch')
964
+ expected_columns = {
965
+ 'row_tables': (('table_token', 2950), ('installation_id', 25),
966
+ ('business_table_oid', 26), ('business_schema_oid', 26),
967
+ ('table_binding', 25), ('issued_count', 20),
968
+ ('record', 3802), ('record_digest', 25)),
969
+ 'archives': (('archive_id', 2950), ('table_token', 2950), ('state', 25),
970
+ ('values_relation_oid', 26), ('row_count', 20),
971
+ ('logical_bytes', 20), ('record', 3802), ('record_digest', 25)),
972
+ 'issued_instances': (('table_token', 2950), ('instance_id', 2950)),
973
+ }
974
+ for table_name, columns in expected_columns.items():
975
+ rows = _all(connection, '''SELECT a.attname,a.attnum,a.attisdropped,
976
+ a.atttypid::pg_catalog.oid,a.atttypmod,a.attnotnull
977
+ FROM pg_catalog.pg_attribute a JOIN pg_catalog.pg_class c ON c.oid=a.attrelid
978
+ JOIN pg_catalog.pg_namespace n ON n.oid=c.relnamespace
979
+ WHERE n.nspname=%s AND c.relname=%s AND a.attnum>0 ORDER BY a.attnum''',
980
+ (self._schema, table_name))
981
+ if (len(rows) != len(columns) or any(
982
+ row != (name, index, False, type_oid, -1, True)
983
+ for index, ((name, type_oid), row) in enumerate(
984
+ zip(columns, rows, strict=True), 1))):
985
+ _fail('row-originals-store-catalog-mismatch')
986
+ for archive_row, record in zip(archive_rows, values_records, strict=True):
987
+ values_relation = _one(connection, '''SELECT c.oid,c.relkind,c.relpersistence,
988
+ c.relowner,c.relrowsecurity,c.relforcerowsecurity,c.relispartition,c.relhassubclass,
989
+ c.relhasrules FROM pg_catalog.pg_class c JOIN pg_catalog.pg_namespace n ON n.oid=c.relnamespace
990
+ WHERE n.nspname=%s AND c.relname=%s''',
991
+ (self._schema, record['valuesRelation']['name']))
992
+ if (values_relation is None or values_relation[0] != archive_row[3]
993
+ or values_relation[1:3] != ('r', 'p')
994
+ or values_relation[3] != self._controller_oid
995
+ or values_relation[4:] != (False, False, False, False, False)):
996
+ _fail('row-originals-archive-catalog-mismatch')
997
+ columns = _all(connection, '''SELECT attname,attnum,attisdropped,
998
+ atttypid::pg_catalog.oid,atttypmod,attnotnull FROM pg_catalog.pg_attribute
999
+ WHERE attrelid=%s AND attnum>0 ORDER BY attnum''', (archive_row[3],))
1000
+ domain = record['sourceNativeDomain']
1001
+ expected_value_columns = (
1002
+ ('instance_id', 2950, -1, True),
1003
+ ('captured_revision', 20, -1, True),
1004
+ ('post_revision', 20, -1, archive_row[2] == 'complete'),
1005
+ ('old_value', domain['typeOid'], domain['typeMod'], False),
1006
+ )
1007
+ if len(columns) != len(expected_value_columns) or any(
1008
+ item[:6] != (name, index, False, oid, typmod, not_null)
1009
+ for index, ((name, oid, typmod, not_null), item) in enumerate(
1010
+ zip(expected_value_columns, columns, strict=True), 1)):
1011
+ _fail('row-originals-archive-catalog-mismatch')
1012
+ self._verify_store_acl(tuple(
1013
+ record['valuesRelation']['name'] for record in values_records),
1014
+ connection=connection)
1015
+
1016
+ def _verify_store_acl(self, values_names: tuple[str, ...] = (), *,
1017
+ connection: Any | None = None) -> None:
1018
+ connection = self._connection if connection is None else connection
1019
+ # Default ACL NULL means only the owner controls the private relation;
1020
+ # explicit PUBLIC grants or extra grantees are rejected.
1021
+ grants = _all(connection, '''SELECT c.relname,acl.grantee,acl.grantor,
1022
+ acl.privilege_type,acl.is_grantable
1023
+ FROM pg_catalog.pg_class c JOIN pg_catalog.pg_namespace n ON n.oid=c.relnamespace
1024
+ CROSS JOIN LATERAL pg_catalog.aclexplode(COALESCE(c.relacl,
1025
+ pg_catalog.acldefault('r',c.relowner))) acl
1026
+ WHERE n.nspname=%s AND c.relkind='r'
1027
+ ORDER BY c.relname,acl.grantee,acl.privilege_type''',
1028
+ (self._schema,))
1029
+ expected = set()
1030
+ for relation in ('row_tables', 'archives', 'issued_instances', *values_names):
1031
+ for privilege in ('INSERT', 'SELECT', 'UPDATE', 'DELETE', 'TRUNCATE',
1032
+ 'REFERENCES', 'TRIGGER', 'MAINTAIN'):
1033
+ # PG18's acldefault records ordinary owner privileges only;
1034
+ # implicit grant authority is not a stored grant option.
1035
+ expected.add((relation, self._controller_oid, self._controller_oid,
1036
+ privilege, False))
1037
+ if set(grants) != expected:
1038
+ _fail('row-originals-store-acl-mismatch')
1039
+ schema_grants = _all(connection, '''SELECT acl.grantee,acl.grantor,
1040
+ acl.privilege_type,acl.is_grantable FROM pg_catalog.pg_namespace n
1041
+ CROSS JOIN LATERAL pg_catalog.aclexplode(COALESCE(n.nspacl,
1042
+ pg_catalog.acldefault('n',n.nspowner))) acl WHERE n.nspname=%s''', (self._schema,))
1043
+ if set(schema_grants) != {
1044
+ (self._controller_oid, self._controller_oid, 'CREATE', False),
1045
+ (self._controller_oid, self._controller_oid, 'USAGE', False)}:
1046
+ _fail('row-originals-store-acl-mismatch')
1047
+
1048
+ def enroll_table(self, *, relation_schema: str, relation_name: str,
1049
+ table_binding: str, installation_id: str,
1050
+ max_issued_instances: int = _MAX_ISSUED) -> EnrolledTable:
1051
+ """Enroll existing rows, reserve every identity and install fixed guard."""
1052
+ self.verify()
1053
+ # Enrollment mutates the business relation and must be bound to the
1054
+ # exact source-derived plan/approval and external object inventory.
1055
+ # That supervisor capability is not part of the currently integrated
1056
+ # adapter, so do not treat caller-supplied relation names as authority.
1057
+ _fail('row-originals-table-enrollment-unavailable')
1058
+
1059
+ # The implementation below is retained as the reviewed finite
1060
+ # construction recipe, but is unreachable until the host supplies the
1061
+ # typed per-table enrollment capability above.
1062
+ if installation_id != self._installation_id:
1063
+ _fail('row-originals-authority-invalid')
1064
+ _safe_int(max_issued_instances, 1, _MAX_ISSUED)
1065
+ for value in (relation_schema, relation_name, table_binding):
1066
+ if type(value) is not str or not value or '\x00' in value:
1067
+ _fail('row-originals-record-invalid')
1068
+ relation = _one(self._connection, '''SELECT c.oid,n.oid,c.relowner,c.relkind,
1069
+ c.relpersistence,c.relrowsecurity,c.relforcerowsecurity,c.relispartition,
1070
+ c.relhassubclass,c.relhasrules,EXISTS(SELECT FROM pg_catalog.pg_trigger t
1071
+ WHERE t.tgrelid=c.oid AND NOT t.tgisinternal)
1072
+ FROM pg_catalog.pg_class c JOIN pg_catalog.pg_namespace n ON n.oid=c.relnamespace
1073
+ WHERE n.nspname=%s AND c.relname=%s FOR UPDATE OF c''', (relation_schema, relation_name))
1074
+ owner = self._authority['payload']['businessOwner']
1075
+ if (relation is None or relation[2] != owner['oid']
1076
+ or relation[3:5] != ('r', 'p')
1077
+ or relation[5] is not True or relation[6] is not True):
1078
+ _fail('row-originals-business-table-unsupported')
1079
+ if relation[7] or relation[8] or relation[9] or relation[10]:
1080
+ _fail('row-originals-business-table-unsupported')
1081
+ if _one(self._connection, 'SELECT count(*) FROM ' + _q(self._schema)
1082
+ + '."row_tables"')[0] >= _MAX_TABLES:
1083
+ _fail('row-originals-table-capacity')
1084
+ if _one(self._connection, 'SELECT count(*) FROM ' + _q(self._schema) + '."archives"')[0] >= _MAX_ARCHIVES:
1085
+ _fail('row-originals-archive-capacity')
1086
+ table_token = str(uuid.uuid4())
1087
+ suffix = table_token.replace('-', '')
1088
+ id_name = '__umf_row_id_' + suffix
1089
+ rev_name = '__umf_row_rev_' + suffix
1090
+ unique_name = '__umf_row_key_' + suffix
1091
+ positive_name = '__umf_row_positive_' + suffix
1092
+ trigger_name = '__umf_row_guard_' + suffix
1093
+ function_name = 'identity_' + suffix
1094
+ collision = _one(self._connection, '''SELECT EXISTS(
1095
+ SELECT 1 FROM pg_catalog.pg_attribute WHERE attrelid=%s AND attname=ANY(%s)
1096
+ AND attnum>0 AND NOT attisdropped)''',
1097
+ (relation[0], [id_name, rev_name]))
1098
+ if collision is None or collision[0]:
1099
+ _fail('row-originals-business-name-conflict')
1100
+ _execute(self._connection, 'LOCK TABLE ' + _q(relation_schema) + '.'
1101
+ + _q(relation_name) + ' IN ACCESS EXCLUSIVE MODE')
1102
+ _execute(self._connection, 'ALTER TABLE ' + _q(relation_schema) + '.' + _q(relation_name)
1103
+ + ' ADD COLUMN ' + _q(id_name) + ' pg_catalog.uuid NOT NULL DEFAULT pg_catalog.gen_random_uuid(), '
1104
+ + 'ADD COLUMN ' + _q(rev_name) + ' pg_catalog.int8 NOT NULL DEFAULT 1')
1105
+ _execute(self._connection, 'ALTER TABLE ' + _q(relation_schema) + '.' + _q(relation_name)
1106
+ + ' ADD CONSTRAINT ' + _q(unique_name) + ' UNIQUE (' + _q(id_name) + '), '
1107
+ + 'ADD CONSTRAINT ' + _q(positive_name) + ' CHECK (' + _q(rev_name) + ' > 0)')
1108
+ # Exact existing-row census runs as the trusted maintenance authority;
1109
+ # this provider never substitutes owner-visible RLS rows for full data.
1110
+ count = _one(self._connection, 'SELECT count(*) FROM ' + _q(relation_schema)
1111
+ + '.' + _q(relation_name))
1112
+ if count is None or type(count[0]) is not int or count[0] > max_issued_instances:
1113
+ _fail('row-originals-issued-capacity')
1114
+ pending = self._reserve_and_install_identity(
1115
+ table_token, max_issued_instances, table_binding,
1116
+ int(relation[0]), int(relation[1]), relation_schema, relation_name,
1117
+ id_name, rev_name, unique_name, positive_name, trigger_name, function_name,
1118
+ count[0])
1119
+ handle = EnrolledTable(_HANDLE_SEAL, self._issuer, table_token=table_token,
1120
+ relation_oid=int(relation[0]), schema_name=relation_schema,
1121
+ table_name=relation_name, id_column=id_name,
1122
+ revision_column=rev_name,
1123
+ max_issued_instances=max_issued_instances)
1124
+ self._tables[id(handle)] = (handle, pending)
1125
+ return handle
1126
+
1127
+ def _resolve_table(self, value: object) -> EnrolledTable:
1128
+ entry = self._tables.get(id(value))
1129
+ if (type(value) is not EnrolledTable or entry is None or entry[0] is not value
1130
+ or value._issuer is not self._issuer):
1131
+ _fail('row-originals-table-handle-required')
1132
+ return value
1133
+
1134
+ def _resolve_archive(self, value: object) -> OriginalArchive:
1135
+ entry = self._archives.get(id(value))
1136
+ if (type(value) is not OriginalArchive or entry is None or entry[0] is not value
1137
+ or value._issuer is not self._issuer):
1138
+ _fail('row-originals-archive-handle-required')
1139
+ return value
1140
+
1141
+ def _verify_enrolled_table(self, table: EnrolledTable) -> dict[str, Any]:
1142
+ """Reconcile immutable table record, native guard and monotonic ledger."""
1143
+ table = self._resolve_table(table)
1144
+ row = _one(self._connection, 'SELECT installation_id,business_table_oid,'
1145
+ 'business_schema_oid,table_binding,issued_count,record,record_digest '
1146
+ 'FROM ' + _q(self._schema)
1147
+ + '."row_tables" WHERE table_token=%s FOR SHARE', (table._table_token,))
1148
+ if row is None:
1149
+ _fail('row-originals-table-unavailable')
1150
+ record = validate_row_table_record(row[5])
1151
+ if (record_digest(record) != row[6] or record['tableToken'] != table._table_token
1152
+ or record['providerId'] != self._provider_id
1153
+ or record['installationId'] != self._installation_id
1154
+ or record['businessRelation']['tableOid'] != row[1]
1155
+ or record['businessRelation']['schemaOid'] != row[2]
1156
+ or row[3] != record['tableBinding']
1157
+ or row[0] != self._installation_id or row[4] > record['maxIssuedInstances']
1158
+ or row[1] != table._relation_oid
1159
+ or record['businessRelation']['schemaName'] != table._schema_name
1160
+ or record['businessRelation']['tableName'] != table._table_name):
1161
+ _fail('row-originals-table-binding-mismatch')
1162
+ if (record['idColumn']['name'] != table._id_column
1163
+ or record['revisionColumn']['name'] != table._revision_column
1164
+ or record['maxIssuedInstances'] != table._max_issued_instances):
1165
+ _fail('row-originals-table-binding-mismatch')
1166
+ actual_columns = _all(self._connection, '''SELECT attnum,attname,atttypid::pg_catalog.oid,
1167
+ atttypmod FROM pg_catalog.pg_attribute WHERE attrelid=%s AND attname=ANY(%s)
1168
+ AND attnum>0 AND NOT attisdropped''',
1169
+ (table._relation_oid, [table._id_column, table._revision_column]))
1170
+ column_map = {item[1]: item for item in actual_columns}
1171
+ if (len(actual_columns) != 2
1172
+ or tuple(column_map.get(table._id_column, ()))
1173
+ != (record['idColumn']['attnum'], table._id_column,
1174
+ record['idColumn']['typeOid'], record['idColumn']['typeMod'])
1175
+ or tuple(column_map.get(table._revision_column, ()))
1176
+ != (record['revisionColumn']['attnum'], table._revision_column,
1177
+ record['revisionColumn']['typeOid'], record['revisionColumn']['typeMod'])):
1178
+ _fail('row-originals-identity-column-mismatch')
1179
+ for key, kind in (('uniqueConstraint', 'u'), ('revisionConstraint', 'c')):
1180
+ constraint = record[key]
1181
+ actual = self._constraint_record(table._relation_oid, constraint['name'], kind)
1182
+ oid = _one(self._connection, 'SELECT oid FROM pg_catalog.pg_constraint '
1183
+ 'WHERE conrelid=%s AND conname=%s',
1184
+ (table._relation_oid, constraint['name']))
1185
+ if (oid is None or oid[0] != constraint['oid'] or actual != constraint):
1186
+ _fail('row-originals-identity-constraint-mismatch')
1187
+ function = record['function']
1188
+ actual_function = _one(self._connection, '''SELECT p.oid,p.proowner,
1189
+ p.prosecdef,p.provolatile,p.proparallel,p.proconfig,pg_catalog.pg_get_functiondef(p.oid)
1190
+ FROM pg_catalog.pg_proc p JOIN pg_catalog.pg_namespace n ON n.oid=p.pronamespace
1191
+ WHERE n.nspname=%s AND p.proname=%s AND p.pronargs=0''',
1192
+ (self._schema, function['name']))
1193
+ if (actual_function is None or actual_function[0] != function['oid']
1194
+ or actual_function[1] != self._controller_oid or not actual_function[2]
1195
+ or actual_function[3] != 'v' or actual_function[4] != 'u'
1196
+ or actual_function[5] != ['search_path=pg_catalog']
1197
+ or hashlib.sha256(actual_function[6].encode('utf-8')).hexdigest()
1198
+ != function['definitionDigest']):
1199
+ _fail('row-originals-identity-guard-mismatch')
1200
+ trigger = record['trigger']
1201
+ actual_trigger = _one(self._connection, '''SELECT t.oid,t.tgfoid,t.tgenabled,
1202
+ pg_catalog.pg_get_triggerdef(t.oid,true) FROM pg_catalog.pg_trigger t
1203
+ WHERE t.tgrelid=%s AND t.tgname=%s AND NOT t.tgisinternal''',
1204
+ (table._relation_oid, trigger['name']))
1205
+ if (actual_trigger is None or actual_trigger[0] != trigger['oid']
1206
+ or actual_trigger[1] != function['oid'] or actual_trigger[2] != 'A'
1207
+ or hashlib.sha256(actual_trigger[3].encode('utf-8')).hexdigest()
1208
+ != trigger['definitionDigest']):
1209
+ _fail('row-originals-identity-guard-mismatch')
1210
+ ledger = _one(self._connection, 'SELECT count(*) FROM ' + _q(self._schema)
1211
+ + '."issued_instances" WHERE table_token=%s', (table._table_token,))
1212
+ live = _one(self._connection, 'SELECT count(*) FROM ' + _q(table._schema_name)
1213
+ + '.' + _q(table._table_name))
1214
+ missing = _one(self._connection, 'SELECT count(*) FROM ' + _q(table._schema_name)
1215
+ + '.' + _q(table._table_name) + ' b WHERE NOT EXISTS (SELECT 1 FROM '
1216
+ + _q(self._schema) + '."issued_instances" i WHERE i.table_token=%s '
1217
+ 'AND i.instance_id=b.' + _q(table._id_column) + ')',
1218
+ (table._table_token,))
1219
+ if (ledger is None or live is None or missing != (0,)
1220
+ or ledger[0] != row[4] or ledger[0] > record['maxIssuedInstances']):
1221
+ _fail('row-originals-issued-ledger-mismatch')
1222
+ return record
1223
+
1224
+ def _reserve_and_install_identity(
1225
+ self, table_token: str, max_issued_instances: int, table_binding: str,
1226
+ relation_oid: int, schema_oid: int, business_schema: str,
1227
+ business_table: str, id_name: str, rev_name: str, unique_name: str,
1228
+ positive_name: str, trigger_name: str, function_name: str,
1229
+ row_count: int) -> dict[str, Any]:
1230
+ """Install identity and ledger atomically; bind all native OIDs afterward."""
1231
+ self._refresh_authority()
1232
+ creation_digest = self._authority.get('creationReservationDigest')
1233
+ _digest(creation_digest)
1234
+ business = _q(business_schema) + '.' + _q(business_table)
1235
+ # No caller-chosen object names are ever used here; all names are the
1236
+ # token-derived fixed profile names checked above.
1237
+ # Build the one exact fixed guard and install it while ACCESS EXCLUSIVE
1238
+ # remains held. No DML can enter before ledger enrollment commits.
1239
+ self._connection.execute(identity_function_sql(
1240
+ self._schema, function_name, token=table_token, table_oid=relation_oid,
1241
+ table_schema=business_schema, table_name=business_table,
1242
+ id_column=id_name, revision_column=rev_name))
1243
+ self._connection.execute('REVOKE ALL ON FUNCTION ' + _q(self._schema) + '.'
1244
+ + _q(function_name) + '() FROM PUBLIC')
1245
+ self._connection.execute('CREATE TRIGGER ' + _q(trigger_name) + ' BEFORE INSERT OR UPDATE ON '
1246
+ + business + ' FOR EACH ROW EXECUTE FUNCTION '
1247
+ + _q(self._schema) + '.' + _q(function_name) + '()')
1248
+ self._connection.execute('ALTER TABLE ' + business + ' ENABLE ALWAYS TRIGGER '
1249
+ + _q(trigger_name))
1250
+ columns = _all(self._connection, '''SELECT attnum,attname,atttypid::pg_catalog.oid,atttypmod
1251
+ FROM pg_catalog.pg_attribute WHERE attrelid=%s AND attname=ANY(%s)
1252
+ AND attnum>0 AND NOT attisdropped''', (relation_oid, [id_name, rev_name]))
1253
+ if len(columns) != 2:
1254
+ _fail('row-originals-identity-column-unobserved')
1255
+ column_map = {row[1]: row for row in columns}
1256
+ id_att, rev_att = column_map.get(id_name), column_map.get(rev_name)
1257
+ if (id_att is None or rev_att is None or id_att[2] != 2950 or id_att[3] != -1
1258
+ or rev_att[2] != 20 or rev_att[3] != -1):
1259
+ _fail('row-originals-identity-column-mismatch')
1260
+ unique = self._constraint_record(relation_oid, unique_name, 'u')
1261
+ positive = self._constraint_record(relation_oid, positive_name, 'c')
1262
+ function = _one(self._connection, '''SELECT p.oid,p.proowner,pg_catalog.pg_get_functiondef(p.oid)
1263
+ FROM pg_catalog.pg_proc p JOIN pg_catalog.pg_namespace n ON n.oid=p.pronamespace
1264
+ WHERE n.nspname=%s AND p.proname=%s AND p.pronargs=0''',
1265
+ (self._schema, function_name))
1266
+ trigger = _one(self._connection, '''SELECT t.oid,pg_catalog.pg_get_triggerdef(t.oid,true),
1267
+ t.tgenabled,t.tgfoid FROM pg_catalog.pg_trigger t
1268
+ WHERE t.tgrelid=%s AND t.tgname=%s AND NOT t.tgisinternal''',
1269
+ (relation_oid, trigger_name))
1270
+ if (function is None or function[1] != self._controller_oid
1271
+ or trigger is None or trigger[2] != 'A' or trigger[3] != function[0]):
1272
+ _fail('row-originals-identity-guard-mismatch')
1273
+ record = {
1274
+ 'profile': ROW_RECORD_PROFILE, 'providerId': self._provider_id,
1275
+ 'installationId': self._installation_id,
1276
+ 'targetCustody': self._authority['targetCustody'],
1277
+ 'tableToken': table_token, 'tableBinding': table_binding,
1278
+ 'businessRelation': {'schemaOid': schema_oid, 'schemaName': business_schema,
1279
+ 'tableOid': relation_oid, 'tableName': business_table},
1280
+ 'idColumn': {'attnum': id_att[0], 'name': id_name,
1281
+ 'typeOid': id_att[2], 'typeMod': id_att[3]},
1282
+ 'revisionColumn': {'attnum': rev_att[0], 'name': rev_name,
1283
+ 'typeOid': rev_att[2], 'typeMod': rev_att[3]},
1284
+ 'uniqueConstraint': unique, 'revisionConstraint': positive,
1285
+ 'trigger': {'oid': trigger[0], 'name': trigger_name,
1286
+ 'definitionDigest': hashlib.sha256(trigger[1].encode('utf-8')).hexdigest()},
1287
+ 'function': {'oid': function[0], 'name': function_name,
1288
+ 'definitionDigest': hashlib.sha256(function[2].encode('utf-8')).hexdigest()},
1289
+ 'creationReservationDigest': creation_digest,
1290
+ 'maxIssuedInstances': max_issued_instances,
1291
+ }
1292
+ validate_row_table_record(record)
1293
+ encoded = _canonical_bytes(record).decode('utf-8')
1294
+ self._connection.execute('INSERT INTO ' + _q(self._schema)
1295
+ + '."row_tables" ("table_token","installation_id",'
1296
+ '"business_table_oid","business_schema_oid","table_binding",'
1297
+ '"issued_count","record","record_digest") '
1298
+ 'VALUES (%s,%s,%s,%s,%s,0,%s::pg_catalog.jsonb,%s)',
1299
+ (table_token, self._installation_id, relation_oid, schema_oid,
1300
+ table_binding, encoded, record_digest(record)))
1301
+ self._connection.execute('INSERT INTO ' + _q(self._schema)
1302
+ + '."issued_instances" ("table_token","instance_id") '
1303
+ 'SELECT %s,' + _q(id_name) + ' FROM ' + business,
1304
+ (table_token,))
1305
+ ledger_count = _one(self._connection, 'SELECT count(*) FROM ' + _q(self._schema)
1306
+ + '."issued_instances" WHERE "table_token"=%s', (table_token,))
1307
+ if ledger_count is None or ledger_count[0] != row_count:
1308
+ _fail('row-originals-ledger-enrollment-mismatch')
1309
+ self._connection.execute('UPDATE ' + _q(self._schema)
1310
+ + '."row_tables" SET "issued_count"=%s '
1311
+ 'WHERE "table_token"=%s AND "issued_count"=0',
1312
+ (row_count, table_token))
1313
+ self._connection.execute('ALTER TABLE ' + business + ' ALTER COLUMN '
1314
+ + _q(id_name) + ' DROP DEFAULT, ALTER COLUMN '
1315
+ + _q(rev_name) + ' DROP DEFAULT')
1316
+ live_missing = _one(self._connection, 'SELECT count(*) FROM ' + business
1317
+ + ' b WHERE NOT EXISTS (SELECT 1 FROM ' + _q(self._schema)
1318
+ + '."issued_instances" i WHERE i."table_token"=%s '
1319
+ 'AND i."instance_id"=b.' + _q(id_name) + ')', (table_token,))
1320
+ if live_missing != (0,):
1321
+ _fail('row-originals-ledger-enrollment-mismatch')
1322
+ return record
1323
+
1324
+ def _constraint_record(self, relation_oid: int, name: str,
1325
+ kind: str) -> dict[str, Any]:
1326
+ row = _one(self._connection, '''SELECT oid,conname,contype,
1327
+ pg_catalog.pg_get_constraintdef(oid,true) FROM pg_catalog.pg_constraint
1328
+ WHERE conrelid=%s AND conname=%s''', (relation_oid, name))
1329
+ if row is None or row[2] != kind:
1330
+ _fail('row-originals-identity-constraint-mismatch')
1331
+ return {'oid': row[0], 'name': row[1],
1332
+ 'definitionDigest': hashlib.sha256(row[3].encode('utf-8')).hexdigest()}
1333
+
1334
+ def capture_originals(self, *, table: EnrolledTable, field: dict[str, str],
1335
+ column_name: str,
1336
+ source_digest: str, target_digest: str, plan_digest: str,
1337
+ approval_digest: str, policy: dict[str, Any],
1338
+ source_native_domain: dict[str, Any]) -> str:
1339
+ """Capture exact native old values; returns only the opaque archive ID."""
1340
+ self.verify()
1341
+ # G04 capture requires an exact same-connection native session receipt
1342
+ # and plan enrollment. The current supervisor API has not yet
1343
+ # finalized that capability; fail before creating archive relations or
1344
+ # reading business rows.
1345
+ _fail('row-originals-session-capability-unavailable')
1346
+
1347
+ # The following typed capture construction is unreachable until that
1348
+ # capability has been integrated and independently reviewed.
1349
+ table = self._resolve_table(table)
1350
+ table_record = self._verify_enrolled_table(table)
1351
+ table_token = _uuid(table._table_token)
1352
+ for digest in (source_digest, target_digest, plan_digest, approval_digest):
1353
+ _digest(digest)
1354
+ if (type(field) is not dict or set(field) != {'module', 'element'}
1355
+ or any(type(value) is not str or not value or '\x00' in value
1356
+ for value in field.values())):
1357
+ _fail('row-originals-record-invalid')
1358
+ _strict_ident(column_name)
1359
+ if type(policy) is not dict or type(source_native_domain) is not dict:
1360
+ _fail('row-originals-record-invalid')
1361
+ if set(policy) != {'id', 'revision'} or any(
1362
+ type(policy[key]) is not str or not policy[key] or '\x00' in policy[key]
1363
+ for key in ('id', 'revision')):
1364
+ _fail('row-originals-record-invalid')
1365
+ # The source native domain must be re-observed and mapped through the
1366
+ # finite pg_catalog scalar renderer. Author type strings are rejected.
1367
+ archive_id = str(uuid.uuid4())
1368
+ relation_name = 'values_' + archive_id.replace('-', '')
1369
+ relation = _one(self._connection, f'''SELECT t.business_schema_oid,t.business_table_oid,
1370
+ n.nspname,c.relname FROM {_q(self._schema)}."row_tables" t
1371
+ JOIN pg_catalog.pg_namespace n ON n.oid=t.business_schema_oid
1372
+ JOIN pg_catalog.pg_class c ON c.oid=t.business_table_oid
1373
+ WHERE t.table_token=%s AND t.installation_id=%s AND t.record_digest ~ '^[a-f0-9]{{64}}$' ''',
1374
+ (table_token, self._installation_id))
1375
+ if (relation is None or relation[3] != table._table_name
1376
+ or relation[2] != table._schema_name):
1377
+ _fail('row-originals-table-binding-mismatch')
1378
+ column = _one(self._connection, '''SELECT a.attnum,t.oid,tn.nspname,t.typname,
1379
+ a.atttypmod,a.attcollation::pg_catalog.oid
1380
+ FROM pg_catalog.pg_attribute a JOIN pg_catalog.pg_type t ON t.oid=a.atttypid
1381
+ JOIN pg_catalog.pg_namespace tn ON tn.oid=t.typnamespace
1382
+ WHERE a.attrelid=%s AND a.attname=%s AND a.attnum>0 AND NOT a.attisdropped''',
1383
+ (table._relation_oid, column_name))
1384
+ if column is None:
1385
+ _fail('row-originals-source-column-mismatch')
1386
+ domain = _exact_object(source_native_domain,
1387
+ {'schema', 'name', 'typeOid', 'typeMod', 'collationOid'})
1388
+ if (column[1] != domain['typeOid'] or column[2] != domain['schema']
1389
+ or column[3] != domain['name'] or column[4] != domain['typeMod']
1390
+ or column[5] != domain['collationOid']):
1391
+ _fail('row-originals-source-column-mismatch')
1392
+ type_sql = _source_type_sql(self._connection, domain)
1393
+ _execute(self._connection, 'CREATE TABLE ' + _q(self._schema) + '.' + _q(relation_name)
1394
+ + ' ("instance_id" pg_catalog.uuid PRIMARY KEY, '
1395
+ + '"captured_revision" pg_catalog.int8 NOT NULL CHECK ("captured_revision" > 0), '
1396
+ + '"post_revision" pg_catalog.int8 CHECK ("post_revision" > 0), '
1397
+ + '"old_value" ' + type_sql + ') USING heap')
1398
+ archive = {
1399
+ 'profile': ARCHIVE_RECORD_PROFILE, 'providerId': self._provider_id,
1400
+ 'installationId': self._installation_id,
1401
+ 'targetCustody': self._authority['targetCustody'],
1402
+ 'archiveId': archive_id, 'tableToken': table_token,
1403
+ 'field': field, 'sourceDigest': source_digest,
1404
+ 'targetDigest': target_digest, 'planDigest': plan_digest,
1405
+ 'approvalDigest': approval_digest, 'policy': policy,
1406
+ 'sourceNativeDomain': source_native_domain,
1407
+ 'valuesRelation': {'schema': self._schema, 'name': relation_name,
1408
+ 'oid': 0},
1409
+ 'creationReservationDigest': table_record['creationReservationDigest'],
1410
+ 'state': 'capturing', 'rowCount': 0, 'logicalBytes': 0,
1411
+ }
1412
+ validate_archive_record(archive)
1413
+ # Native, full-row capture is performed by the enrolled host session;
1414
+ # no row value is returned through this provider API.
1415
+ self._capture_rows_as_native(table, column_name, relation_name, archive)
1416
+ handle = OriginalArchive(_HANDLE_SEAL, self._issuer, archive_id, table_token)
1417
+ self._archives[id(handle)] = (handle, archive)
1418
+ return handle
1419
+
1420
+ def _capture_rows_as_native(self, table: EnrolledTable, column_name: str,
1421
+ values_name: str, archive: dict[str, Any]) -> None:
1422
+ # This exact private maintenance hook will be enabled by the concrete
1423
+ # same-connection supervisor adapter; no caller callback is accepted.
1424
+ self._refresh_authority()
1425
+ self._capture_rows(table, column_name, values_name, archive)
1426
+
1427
+ def _capture_rows(self, table: EnrolledTable, column_name: str,
1428
+ values_name: str, archive: dict[str, Any]) -> None:
1429
+ """Unavailable until a reviewed same-connection session capability exists."""
1430
+ _fail('row-originals-session-capability-unavailable')
1431
+
1432
+ def record_post_conversion_baseline(self, archive_id: OriginalArchive, *,
1433
+ table: EnrolledTable) -> None:
1434
+ """Bind the post-conversion revision baseline before phase commit."""
1435
+ self.verify()
1436
+ _fail('row-originals-session-capability-unavailable')
1437
+ archive = self._resolve_archive(archive_id)
1438
+ table = self._resolve_table(table)
1439
+ self._verify_enrolled_table(table)
1440
+ if archive._table_token != table._table_token:
1441
+ _fail('row-originals-archive-binding-mismatch')
1442
+ self._refresh_authority()
1443
+ _complete_archive_baseline(self._connection, self._schema, archive._archive_id, table)
1444
+
1445
+ def inspect_restore(self, archive_id: OriginalArchive, *, table: EnrolledTable) -> None:
1446
+ """Strictly preflight full row identity/revision correspondence.
1447
+
1448
+ G04 restores never expose original values to callers. The eventual
1449
+ restore executor consumes them inside the source-bound native phase.
1450
+ """
1451
+ self.verify()
1452
+ _fail('row-originals-session-capability-unavailable')
1453
+ archive = self._resolve_archive(archive_id)
1454
+ table = self._resolve_table(table)
1455
+ self._verify_enrolled_table(table)
1456
+ if archive._table_token != table._table_token:
1457
+ _fail('row-originals-archive-binding-mismatch')
1458
+ _strict_restore_preflight(self._connection, self._schema, archive._archive_id, table)
1459
+
1460
+ def purge(self, _archive_id: str) -> None:
1461
+ """Value purge is G05 and is intentionally not an operation in .1."""
1462
+ _fail('row-originals-purge-unavailable')
1463
+
1464
+
1465
+ def _source_type_sql(connection: Any, domain: dict[str, Any]) -> str:
1466
+ required = {'schema', 'name', 'typeOid', 'typeMod', 'collationOid'}
1467
+ item = _exact_object(domain, required)
1468
+ oid = _safe_int(item['typeOid'], 1, 2**32 - 1)
1469
+ typmod = _safe_int(item['typeMod'], -1, 2**31 - 1)
1470
+ collation_oid = _safe_int(item['collationOid'], 0, 2**32 - 1)
1471
+ observed = _one(connection, '''SELECT tn.nspname,t.typname,t.typtype,t.typbasetype,
1472
+ t.typtypmod,t.typcollation::pg_catalog.oid,co.collname,cn.nspname
1473
+ FROM pg_catalog.pg_type t JOIN pg_catalog.pg_namespace tn ON tn.oid=t.typnamespace
1474
+ LEFT JOIN pg_catalog.pg_collation co ON co.oid=t.typcollation
1475
+ LEFT JOIN pg_catalog.pg_namespace cn ON cn.oid=co.collnamespace
1476
+ WHERE t.oid=%s''', (oid,))
1477
+ if observed is None or observed[0] != item['schema'] or observed[1] != item['name']:
1478
+ _fail('row-originals-native-domain-mismatch')
1479
+ if observed[2] != 'b' or observed[3] != 0:
1480
+ _fail('row-originals-native-domain-unsupported')
1481
+ kind, name = observed[0], observed[1]
1482
+ if kind != 'pg_catalog':
1483
+ _fail('row-originals-native-domain-unsupported')
1484
+ simple = {'int2': 'pg_catalog.int2', 'int4': 'pg_catalog.int4',
1485
+ 'int8': 'pg_catalog.int8', 'uuid': 'pg_catalog.uuid',
1486
+ 'bool': 'pg_catalog.bool', 'date': 'pg_catalog.date',
1487
+ 'timestamptz': 'pg_catalog.timestamptz'}
1488
+ if name in simple and typmod == -1 and collation_oid == 0:
1489
+ return simple[name]
1490
+ if (name == 'text' and typmod == -1 and observed[5] == collation_oid
1491
+ and observed[6:8] == ('C', 'pg_catalog')):
1492
+ return 'pg_catalog.text COLLATE pg_catalog."C"'
1493
+ if name == 'numeric' and typmod >= 4 and collation_oid == 0:
1494
+ packed = typmod - 4
1495
+ precision = (packed >> 16) & 0xFFFF
1496
+ scale = packed & 0x7FF
1497
+ if scale >= 0x400:
1498
+ scale -= 0x800
1499
+ if 1 <= precision <= 1000 and -1000 <= scale <= 1000:
1500
+ return f'pg_catalog.numeric({precision},{scale})'
1501
+ _fail('row-originals-native-domain-unsupported')
1502
+
1503
+
1504
+ def _strict_restore_preflight(connection: Any, schema: str, archive_id: str,
1505
+ table: EnrolledTable) -> None:
1506
+ archive = _one(connection, 'SELECT table_token,state,values_relation_oid,record,record_digest '
1507
+ 'FROM ' + _q(schema) + '."archives" WHERE archive_id=%s FOR SHARE',
1508
+ (archive_id,))
1509
+ if archive is None or str(archive[0]) != table._table_token or archive[1] != 'complete':
1510
+ _fail('row-originals-archive-unavailable')
1511
+ record = archive[3]
1512
+ validate_archive_record(record)
1513
+ if record_digest(record) != archive[4]:
1514
+ _fail('row-originals-archive-corrupt')
1515
+ values = record['valuesRelation']
1516
+ if (type(values) is not dict or values.get('schema') != schema
1517
+ or type(values.get('name')) is not str or values.get('oid') != archive[2]):
1518
+ _fail('row-originals-archive-corrupt')
1519
+ values_name = values['name']
1520
+ _strict_ident(values_name)
1521
+ table_ident = _q(table._schema_name) + '.' + _q(table._table_name)
1522
+ values_ident = _q(schema) + '.' + _q(values_name)
1523
+ rows = _one(connection, 'SELECT count(*) FROM ' + table_ident)
1524
+ archived = _one(connection, 'SELECT count(*) FROM ' + values_ident)
1525
+ mismatch_sql = ('SELECT count(*) FROM (('
1526
+ 'SELECT ' + _q(table._id_column) + ' AS id FROM ' + table_ident
1527
+ + ' EXCEPT SELECT "instance_id" FROM ' + values_ident + ') UNION ALL ('
1528
+ 'SELECT "instance_id" AS id FROM ' + values_ident
1529
+ + ' EXCEPT SELECT ' + _q(table._id_column) + ' FROM ' + table_ident
1530
+ + ')) mismatch')
1531
+ mismatches = _one(connection, mismatch_sql)
1532
+ stale = _one(connection, 'SELECT count(*) FROM ' + table_ident + ' b JOIN '
1533
+ + values_ident + ' v ON b.' + _q(table._id_column)
1534
+ + ' = v."instance_id" WHERE v."post_revision" IS NULL OR b.'
1535
+ + _q(table._revision_column) + ' <> v."post_revision"')
1536
+ if (rows is None or archived is None or mismatches is None or stale is None
1537
+ or rows[0] != archived[0] or mismatches[0] != 0 or stale[0] != 0
1538
+ or rows[0] != record['rowCount']):
1539
+ _fail('row-originals-restore-conflict')
1540
+
1541
+
1542
+ def _complete_archive_baseline(connection: Any, schema: str, archive_id: str,
1543
+ table: EnrolledTable) -> None:
1544
+ """Record complete actual post-conversion revisions and bounded accounting."""
1545
+ row = _one(connection, 'SELECT a.table_token,a.state,a.values_relation_oid,a.row_count,'
1546
+ 'a.record,a.record_digest FROM ' + _q(schema)
1547
+ + '."archives" a WHERE a.archive_id=%s FOR UPDATE', (archive_id,))
1548
+ if row is None or str(row[0]) != table._table_token or row[1] != 'capturing':
1549
+ _fail('row-originals-archive-binding-mismatch')
1550
+ record = row[4]
1551
+ validate_archive_record(record)
1552
+ if record_digest(record) != row[5] or record['archiveId'] != archive_id:
1553
+ _fail('row-originals-archive-corrupt')
1554
+ values = record['valuesRelation']
1555
+ values_relation = _one(connection, '''SELECT c.oid,c.relkind,c.relpersistence,
1556
+ c.relowner,c.relrowsecurity,c.relforcerowsecurity,c.relispartition,c.relhassubclass,
1557
+ c.relhasrules FROM pg_catalog.pg_class c JOIN pg_catalog.pg_namespace n ON n.oid=c.relnamespace
1558
+ WHERE n.nspname=%s AND c.relname=%s''', (schema, values['name']))
1559
+ if (values_relation is None or values_relation[0] != row[2]
1560
+ or values['oid'] != row[2] or values_relation[1:3] != ('r', 'p')
1561
+ or values_relation[3] <= 0 or values_relation[4:] != (False, False, False, False, False)):
1562
+ _fail('row-originals-archive-catalog-mismatch')
1563
+ values_ident = _q(schema) + '.' + _q(values['name'])
1564
+ business = _q(table._schema_name) + '.' + _q(table._table_name)
1565
+ instance = _q(table._id_column)
1566
+ revision = _q(table._revision_column)
1567
+ # Full identity equality is required before setting the post-cutover marker.
1568
+ difference = _one(connection, 'SELECT count(*) FROM (('
1569
+ 'SELECT ' + instance + ' AS id FROM ' + business
1570
+ + ' EXCEPT SELECT "instance_id" FROM ' + values_ident
1571
+ + ') UNION ALL (SELECT "instance_id" AS id FROM ' + values_ident
1572
+ + ' EXCEPT SELECT ' + instance + ' FROM ' + business + ')) d')
1573
+ current_count = _one(connection, 'SELECT count(*) FROM ' + business)
1574
+ value_count = _one(connection, 'SELECT count(*) FROM ' + values_ident)
1575
+ if (difference != (0,) or current_count is None or value_count is None
1576
+ or current_count != value_count or current_count[0] != row[3]
1577
+ or current_count[0] != record['rowCount']):
1578
+ _fail('row-originals-restore-conflict')
1579
+ updated = _one(connection, 'WITH changed AS (UPDATE ' + values_ident
1580
+ + ' v SET "post_revision"=b.' + revision + ' FROM ' + business
1581
+ + ' b WHERE b.' + instance + '=v."instance_id" '
1582
+ 'AND v."post_revision" IS NULL RETURNING 1) SELECT count(*) FROM changed')
1583
+ if updated is None or updated[0] != record['rowCount']:
1584
+ _fail('row-originals-post-revision-mismatch')
1585
+ unbound = _one(connection, 'SELECT count(*) FROM ' + values_ident
1586
+ + ' WHERE "post_revision" IS NULL')
1587
+ if unbound != (0,):
1588
+ _fail('row-originals-post-revision-mismatch')
1589
+ connection.execute('ALTER TABLE ' + values_ident
1590
+ + ' ALTER COLUMN "post_revision" SET NOT NULL')
1591
+ # Fix output formatting independently of session defaults before measuring
1592
+ # canonical native text bytes for the logical-retention projection.
1593
+ connection.execute("SET LOCAL TimeZone TO 'UTC'")
1594
+ connection.execute("SET LOCAL DateStyle TO 'ISO, YMD'")
1595
+ byte_rows = _all(connection, 'SELECT CASE WHEN "old_value" IS NULL THEN 0 '
1596
+ 'ELSE pg_catalog.octet_length(pg_catalog.convert_to('
1597
+ '"old_value"::pg_catalog.text,\'UTF8\')) END '
1598
+ 'FROM ' + values_ident)
1599
+ scalar_bytes = sum(row_value[0] for row_value in byte_rows)
1600
+ complete_record = {**record, 'state': 'complete', 'rowCount': current_count[0]}
1601
+ complete_record.pop('logicalBytes')
1602
+ logical_bytes = len(_canonical_bytes(complete_record)) + 41 * current_count[0] + scalar_bytes
1603
+ if logical_bytes > _MAX_LOGICAL_BYTES:
1604
+ _fail('row-originals-logical-capacity')
1605
+ complete_record['logicalBytes'] = logical_bytes
1606
+ validate_archive_record(complete_record)
1607
+ connection.execute('UPDATE ' + _q(schema) + '."archives" SET "state"=%s,'
1608
+ '"row_count"=%s,"logical_bytes"=%s,"record"=%s::pg_catalog.jsonb,'
1609
+ '"record_digest"=%s WHERE "archive_id"=%s AND "state"=%s',
1610
+ ('complete', current_count[0], logical_bytes,
1611
+ _canonical_bytes(complete_record).decode('utf-8'),
1612
+ record_digest(complete_record), archive_id, 'capturing'))
1613
+ final = _one(connection, 'SELECT state,row_count,logical_bytes,record,record_digest '
1614
+ 'FROM ' + _q(schema) + '."archives" WHERE archive_id=%s', (archive_id,))
1615
+ if (final is None or final[0] != 'complete' or final[1] != current_count[0]
1616
+ or final[2] != logical_bytes or final[3] != complete_record
1617
+ or final[4] != record_digest(complete_record)):
1618
+ _fail('row-originals-archive-finalize-unverified')
1619
+
1620
+
1621
+ def _strict_ident(value: str) -> str:
1622
+ if type(value) is not str or not value or '\x00' in value:
1623
+ _fail('row-originals-record-invalid')
1624
+ return value
1625
+
1626
+
1627
+ def open_originals_store_recovery(supervisor: object, connection: object, *,
1628
+ provider_id: str) -> object:
1629
+ """Issue a restricted provider for one exact original store journal key."""
1630
+ try:
1631
+ from .ingress_local_postgres import (
1632
+ LocalPostgresError,
1633
+ LocalPostgresSupervisor,
1634
+ _store_descriptor,
1635
+ )
1636
+ except ImportError:
1637
+ _fail('row-originals-store-recovery-unavailable')
1638
+ if type(supervisor) is not LocalPostgresSupervisor:
1639
+ _fail('row-originals-store-recovery-unavailable')
1640
+ with supervisor._original_control_lease(operation_kind='store'):
1641
+ supervisor._require_original_control_lease(operation_kind='store')
1642
+ if (type(provider_id) is not str
1643
+ or provider_id != supervisor._provider_id
1644
+ or supervisor._journal is None or supervisor._custodian is None
1645
+ or (supervisor._custody_handle is None
1646
+ and supervisor._pending_original_store_recovery is None)):
1647
+ raise LocalPostgresError(
1648
+ 'local-postgresql-store-recovery-unavailable')
1649
+ target = (supervisor._custody_handle if supervisor._custody_handle is not None
1650
+ else supervisor._pending_original_store_recovery[0])
1651
+ supervisor._require_original_store_recovery_target(target)
1652
+ try:
1653
+ from psycopg import Connection
1654
+ if type(connection) is not Connection or connection.closed:
1655
+ raise LocalPostgresError(
1656
+ 'local-postgresql-store-recovery-connection-invalid')
1657
+ if int(connection.info.transaction_status) != 0:
1658
+ raise LocalPostgresError(
1659
+ 'local-postgresql-store-readonly-transaction-active')
1660
+ from .ingress_custody import JOURNAL_PROFILE_02, _replay
1661
+ target_reference = supervisor._custodian._public_reference(
1662
+ target)
1663
+ verified_target = supervisor._custodian._resolve_target_custody(
1664
+ target)
1665
+ if (verified_target.reference != target_reference
1666
+ or target_reference.get('custodianId') != supervisor._custodian_id
1667
+ or target_reference.get('resourceId') is None
1668
+ or target_reference.get('incarnation') is None):
1669
+ raise LocalPostgresError(
1670
+ 'local-postgresql-store-recovery-target-invalid')
1671
+ store = _store_descriptor(STORE_PROFILE, provider_id)
1672
+ external_doc = supervisor._custodian._journal._load()
1673
+ external = _replay(
1674
+ external_doc['events'], profile=JOURNAL_PROFILE_02)
1675
+ key = (target_reference['registrationId'], supervisor._provider_id,
1676
+ supervisor._bound_installation_id, store['profile'],
1677
+ store['storeId'], store['schemaName'])
1678
+ matches = [(candidate, state) for candidate, state
1679
+ in external['stores'].items() if candidate == key]
1680
+ if len(matches) != 1:
1681
+ raise LocalPostgresError(
1682
+ 'local-postgresql-store-recovery-outcome-unresolved')
1683
+ _selected_key, state = matches[0]
1684
+ reserved_events = [event for event in external_doc['events']
1685
+ if event['kind'] == 'originals-store-reserved'
1686
+ and event['payload']['reservation']['reservationId']
1687
+ == state.get('id')]
1688
+ if (state.get('status') not in {
1689
+ 'reserved', 'observed-committed', 'confirmed'}
1690
+ or len(reserved_events) != 1
1691
+ or reserved_events[0]['payload']['reservation'].get('store') != store
1692
+ or reserved_events[0]['payload']['reservation'].get(
1693
+ 'targetCustody') != target_reference):
1694
+ raise LocalPostgresError(
1695
+ 'local-postgresql-store-recovery-prefix-invalid')
1696
+ supervisor_intent = next((event['payload']
1697
+ for event in supervisor._journal.read()['events']
1698
+ if event['kind'] == 'creation-intent'), None)
1699
+ if type(supervisor_intent) is not dict:
1700
+ raise LocalPostgresError(
1701
+ 'local-postgresql-store-recovery-unavailable')
1702
+ return PgRowOriginalsStore._from_recovery(
1703
+ _RECOVERY_PROVIDER_SEAL, supervisor=supervisor,
1704
+ connection=connection, provider_id=provider_id,
1705
+ installation_id=supervisor._bound_installation_id,
1706
+ controller_role=supervisor_intent['controllerName'],
1707
+ custodian=supervisor._custodian, target=target)
1708
+ except LocalPostgresError:
1709
+ raise
1710
+ except Exception: # noqa: BLE001 -- no authority from malformed prefix
1711
+ raise LocalPostgresError(
1712
+ 'local-postgresql-store-recovery-unavailable') from None