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,185 @@
1
+ # SPDX-License-Identifier: MIT OR Apache-2.0
2
+ """Host-neutral G11 generation-ingress capability interfaces.
3
+
4
+ This module defines typing boundaries only. Structural protocol conformance or
5
+ an instance of an opaque handle is not trusted provider/custodian evidence and
6
+ does not authorize native .6 execution. The production host remains fail-closed
7
+ until a concrete provider verifies issuer identity, target custody, native
8
+ receipts and the selected execution profile.
9
+ """
10
+ from __future__ import annotations
11
+
12
+ from contextlib import AbstractContextManager
13
+ from typing import Any, Protocol, runtime_checkable
14
+
15
+ _CAPABILITY_SEAL = object()
16
+
17
+
18
+ class _OpaqueCapability:
19
+ """Non-serializable handle base; no public/dictionary minting constructor."""
20
+
21
+ __slots__ = ('__issuer', '__kind')
22
+
23
+ def __init__(self, seal: object, issuer: object, kind: str):
24
+ if seal is not _CAPABILITY_SEAL or issuer is None or type(kind) is not str:
25
+ raise TypeError('capability handles are issued by a trusted provider')
26
+ object.__setattr__(self, '_OpaqueCapability__issuer', issuer)
27
+ object.__setattr__(self, '_OpaqueCapability__kind', kind)
28
+
29
+ def __setattr__(self, name: str, value: object) -> None:
30
+ raise AttributeError('opaque capabilities are immutable')
31
+
32
+ def __reduce_ex__(self, protocol: int):
33
+ raise TypeError('opaque capabilities cannot be serialized')
34
+
35
+ def _issued_by(self, issuer: object, kind: str) -> bool:
36
+ return (self.__issuer is issuer and self.__kind == kind
37
+ and type(self) is not _OpaqueCapability)
38
+
39
+ def __repr__(self) -> str:
40
+ return f'<{type(self).__name__} opaque>'
41
+
42
+
43
+ class TargetCustody(_OpaqueCapability):
44
+ """Opaque external registration for one physical installation incarnation."""
45
+
46
+
47
+ class OwnerEnrollmentRequest(_OpaqueCapability):
48
+ """Trusted owner-side request used before a custodian issues TargetCustody.
49
+
50
+ This is not a native enrollment or a custody capability. A future concrete
51
+ owner-side issuer must create it from authenticated registration intent;
52
+ caller dictionaries and structural protocol conformance cannot mint it.
53
+ """
54
+
55
+
56
+ class TargetReservation(_OpaqueCapability):
57
+ """Opaque durable reservation of the original transition intent."""
58
+
59
+
60
+ class GenerationEnrollment(_OpaqueCapability):
61
+ """Opaque enrollment of exact stable subject identities and target."""
62
+
63
+
64
+ class EpochProvisionRequest(_OpaqueCapability):
65
+ """Custodian-bound original disabled-epoch request and separate approval.
66
+
67
+ A concrete provider may issue this handle only after validating and
68
+ retaining the exact closed provisioning request and its approval binding.
69
+ It is a distinct pre-OID authority, not a final transition request.
70
+ """
71
+
72
+
73
+ class EpochProvisionReservation(_OpaqueCapability):
74
+ """External reservation of one original epoch-provision request/approval."""
75
+
76
+
77
+ class PreparedGenerationEpoch(_OpaqueCapability):
78
+ """Opaque receipt for an exact newly provisioned disabled login epoch."""
79
+
80
+
81
+ class GenerationIngressRequest(_OpaqueCapability):
82
+ """Opaque source/plan/approval/policy binding for one transition."""
83
+
84
+
85
+ class GenerationTransition(_OpaqueCapability):
86
+ """Opaque original intent/reservation pair; never author-serializable."""
87
+
88
+
89
+ class GenerationFenceReceipt(_OpaqueCapability):
90
+ """Opaque native proof of a committed admission fence and retirement."""
91
+
92
+
93
+ class GenerationAdmission(_OpaqueCapability):
94
+ """Opaque fresh credential/factory admission for a committed generation."""
95
+
96
+
97
+ class GenerationObservation(Protocol):
98
+ """Read-only status whose concrete issuer must be independently checked."""
99
+
100
+
101
+ @runtime_checkable
102
+ class GenerationIngressLease(Protocol):
103
+ """One provider lease for fencing, per-phase hooks, and publication hooks."""
104
+
105
+ def observe(self) -> GenerationObservation: ...
106
+
107
+ def fence_and_retire(self, deadline: object) -> GenerationFenceReceipt: ...
108
+
109
+ def require_fenced(self, native_phase_connection: Any,
110
+ catalog_side: str) -> None: ...
111
+
112
+ def record_phase(self, native_phase_connection: Any,
113
+ verified_phase_receipt: object) -> None: ...
114
+
115
+ def record_publication(self, native_final_connection: Any,
116
+ verified_reference: object) -> None: ...
117
+
118
+
119
+ @runtime_checkable
120
+ class GenerationIngressProvider(Protocol):
121
+ """Trusted provider API; the Protocol is not itself a capability check."""
122
+
123
+ @property
124
+ def provider_id(self) -> str: ...
125
+
126
+ def enroll_installation(self, enrollment_request: object,
127
+ enrollment_approval: object) -> GenerationEnrollment: ...
128
+
129
+ def prepare_epoch_provision_request(
130
+ self, enrollment: GenerationEnrollment, closed_request: object,
131
+ provisioning_approval: object) -> EpochProvisionRequest: ...
132
+
133
+ # The custodian reservation is required before this method can perform
134
+ # native work; its separate authority is not interchangeable with the
135
+ # later GenerationIngressRequest/TargetReservation pair.
136
+ def provision_disabled_epoch(self, enrollment: GenerationEnrollment,
137
+ provision_request: EpochProvisionRequest,
138
+ reservation: EpochProvisionReservation,
139
+ provisioning_approval: object) -> PreparedGenerationEpoch: ...
140
+
141
+ def transition_request(self, plan_request: object,
142
+ enrollment: GenerationEnrollment,
143
+ prepared_epoch: PreparedGenerationEpoch,
144
+ plan_approval: object) -> GenerationIngressRequest: ...
145
+
146
+ def prepare_transition(self, request: GenerationIngressRequest,
147
+ enrollment: GenerationEnrollment,
148
+ ingress_approval: object) -> GenerationTransition: ...
149
+
150
+ def acquire(self, transition: GenerationTransition) -> AbstractContextManager[GenerationIngressLease]: ...
151
+
152
+ def admit(self, authenticated_subject: object, expected_reference: object,
153
+ purpose: str) -> GenerationAdmission: ...
154
+
155
+
156
+ @runtime_checkable
157
+ class TargetCustodian(Protocol):
158
+ """External physical-target custody and append-only transition authority."""
159
+
160
+ @property
161
+ def custodian_id(self) -> str: ...
162
+
163
+ def register_target(self, owner_enrollment: OwnerEnrollmentRequest) -> TargetCustody: ...
164
+
165
+ def reserve_epoch_provision(
166
+ self, request: EpochProvisionRequest,
167
+ provisioning_approval: object) -> EpochProvisionReservation: ...
168
+
169
+ # These methods reconcile the original pre-OID reservation. They must not
170
+ # be implemented by wrapping the later transition observation API.
171
+ def observe_epoch_provision(
172
+ self, target: TargetCustody,
173
+ reservation: EpochProvisionReservation) -> GenerationObservation: ...
174
+
175
+ def confirm_epoch_provision(
176
+ self, reservation: EpochProvisionReservation,
177
+ native_receipt: object) -> GenerationObservation: ...
178
+
179
+ def reserve_transition(self, request: GenerationIngressRequest,
180
+ ingress_approval: object) -> TargetReservation: ...
181
+
182
+ def observe(self, target: TargetCustody) -> GenerationObservation: ...
183
+
184
+ def confirm_transition(self, reservation: TargetReservation,
185
+ native_receipt: object) -> GenerationObservation: ...
@@ -0,0 +1,138 @@
1
+ """Pure source-level transitions for the governed generation ROOT registry.
2
+
3
+ These functions transform caller-supplied canonical bytes. They do not provide
4
+ persistence, locking, compare-and-swap, authority, or native custody.
5
+ """
6
+ from __future__ import annotations
7
+
8
+ from typing import Any
9
+
10
+ from umf_access.lifecycle import generation_authority_bootstrap as root
11
+
12
+
13
+ def _context(raw: bytes, *, registry_id: str, anchor_digest: str,
14
+ root_policy: object, purpose: str,
15
+ bootstrap_enrollment_id: str) -> dict[str, Any]:
16
+ root.validate_registry(raw, registry_id=registry_id, anchor_digest=anchor_digest,
17
+ root_policy=root_policy, purpose=purpose,
18
+ bootstrap_enrollment_id=bootstrap_enrollment_id)
19
+ return root._parse(raw)
20
+
21
+
22
+ def reserve_prepared(raw: bytes, request: object, *, registry_id: str,
23
+ anchor_digest: str, root_policy: object, purpose: str,
24
+ bootstrap_enrollment_id: str) -> bytes:
25
+ """Append one exact prepared request, or return bytes unchanged on replay."""
26
+ value = _context(raw, registry_id=registry_id, anchor_digest=anchor_digest,
27
+ root_policy=root_policy, purpose=purpose,
28
+ bootstrap_enrollment_id=bootstrap_enrollment_id)
29
+ # Canonical copying rejects non-JSON containers and floats before any Python
30
+ # equality/hash operation can treat them as equivalent to signed JSON values.
31
+ candidate_bytes = root._root_canonical(request, maximum=root._MAX_REQUEST)
32
+ candidate_request = root._parse(candidate_bytes)
33
+ root._closed(candidate_request, {
34
+ 'requestId', 'enrollmentId', 'contextId', 'effectKey', 'intent', 'payload',
35
+ 'state', 'reservedSequence', 'confirmedSequence', 'approvalEnvelope'},
36
+ 'generation-root-registry-invalid')
37
+ if (candidate_request['state'] != 'prepared'
38
+ or candidate_request['confirmedSequence'] is not None
39
+ or candidate_request['approvalEnvelope'] is not None):
40
+ root._fail('generation-root-registry-invalid')
41
+ reserve_sequence = candidate_request['reservedSequence']
42
+ if (type(reserve_sequence) is not int
43
+ or not 1 <= reserve_sequence <= root._MAX_SAFE):
44
+ root._fail('generation-root-registry-sequence-invalid')
45
+ request_id = root._uuid(candidate_request['requestId'])
46
+ root._uuid(candidate_request['enrollmentId'])
47
+ root._uuid(candidate_request['contextId'])
48
+ effect_key = candidate_request['effectKey']
49
+ if (type(effect_key) is not list or len(effect_key) != 6
50
+ or any(type(part) is not str or not part for part in effect_key)):
51
+ root._fail('generation-root-registry-invalid')
52
+ for part in effect_key:
53
+ root._root_text(part, 256)
54
+ intent, trust, configuration = root._validate_root_intent(
55
+ candidate_request['intent'], request=candidate_request)
56
+ root._validate_root_payload(
57
+ candidate_request['payload'], intent=intent, trust=trust,
58
+ configuration=configuration, effect=effect_key, root_policy=root_policy,
59
+ purpose=purpose, bootstrap_enrollment_id=bootstrap_enrollment_id)
60
+ existing_by_id = {item['requestId']: item for item in value['requests']}
61
+ existing_by_effect = {tuple(item['effectKey']): item for item in value['requests']}
62
+ effect_identity = tuple(effect_key)
63
+ if request_id in existing_by_id:
64
+ existing = existing_by_id[request_id]
65
+ stable_existing = {k: v for k, v in existing.items()
66
+ if k not in ('state', 'confirmedSequence', 'approvalEnvelope')}
67
+ stable_candidate = {k: v for k, v in candidate_request.items()
68
+ if k not in ('state', 'confirmedSequence', 'approvalEnvelope')}
69
+ if root._root_canonical(stable_candidate) == root._root_canonical(stable_existing):
70
+ return raw
71
+ root._fail('generation-root-registry-duplicate-identity')
72
+ if effect_identity in existing_by_effect:
73
+ root._fail('generation-root-registry-duplicate-effect')
74
+ if (len(value['requests']) >= root._MAX_REQUESTS
75
+ or value['sequence'] >= root._MAX_SAFE
76
+ or reserve_sequence != value['sequence'] + 1):
77
+ root._fail('generation-root-registry-sequence-invalid')
78
+ updated = dict(value)
79
+ updated['requests'] = [*value['requests'], candidate_request]
80
+ updated['sequence'] = value['sequence'] + 1
81
+ encoded = root._root_canonical(updated)
82
+ _context(encoded, registry_id=registry_id, anchor_digest=anchor_digest,
83
+ root_policy=root_policy, purpose=purpose,
84
+ bootstrap_enrollment_id=bootstrap_enrollment_id)
85
+ return encoded
86
+
87
+
88
+ def confirm_prepared(raw: bytes, request_id: str, envelope: object, *,
89
+ registry_id: str, anchor_digest: str, root_policy: object,
90
+ purpose: str, bootstrap_enrollment_id: str) -> bytes:
91
+ """Confirm one prepared request with a verified signed envelope."""
92
+ value = _context(raw, registry_id=registry_id, anchor_digest=anchor_digest,
93
+ root_policy=root_policy, purpose=purpose,
94
+ bootstrap_enrollment_id=bootstrap_enrollment_id)
95
+ request_id = root._uuid(request_id)
96
+ envelope_bytes = root._root_canonical(envelope, maximum=16_384)
97
+ envelope_value = root._parse(envelope_bytes)
98
+ matches = [item for item in value['requests'] if item['requestId'] == request_id]
99
+ if len(matches) != 1:
100
+ root._fail('generation-root-registry-invalid')
101
+ current = matches[0]
102
+ if current['state'] == 'confirmed':
103
+ current_envelope_bytes = root._root_canonical(
104
+ current['approvalEnvelope'], maximum=16_384)
105
+ if envelope_bytes == current_envelope_bytes:
106
+ return raw
107
+ root._fail('generation-root-registry-crosslink-invalid')
108
+ if (current['state'] != 'prepared'
109
+ or value['sequence'] >= root._MAX_SAFE
110
+ or len(value['enrollments']) >= root._MAX_ENROLLMENTS):
111
+ root._fail('generation-root-registry-invalid')
112
+ updated = root._json_copy(value)
113
+ target = next(item for item in updated['requests'] if item['requestId'] == request_id)
114
+ target['state'] = 'confirmed'
115
+ target['confirmedSequence'] = value['sequence'] + 1
116
+ target['approvalEnvelope'] = envelope_value
117
+ intent = target['intent']
118
+ trust = intent['trust']
119
+ payload = target['payload']
120
+ enrollment = {
121
+ 'profile': root.ROOT_ENROLLMENT_PROFILE,
122
+ 'enrollmentId': target['enrollmentId'], 'requestId': target['requestId'],
123
+ 'contextId': target['contextId'],
124
+ 'bootstrapEnrollmentId': bootstrap_enrollment_id,
125
+ 'rootPolicyDigest': payload['rootPolicyDigest'],
126
+ 'rootApprovalDigest': root._sha(envelope_bytes),
127
+ 'trust': trust, 'configuration': intent['configuration'],
128
+ 'configurationDigest': intent['configurationDigest'],
129
+ 'nativeEvidenceDigest': intent['nativeEvidenceDigest'],
130
+ 'state': 'confirmed', 'registrySequence': value['sequence'] + 1,
131
+ }
132
+ updated['enrollments'].append(enrollment)
133
+ updated['sequence'] = value['sequence'] + 1
134
+ encoded = root._root_canonical(updated)
135
+ _context(encoded, registry_id=registry_id, anchor_digest=anchor_digest,
136
+ root_policy=root_policy, purpose=purpose,
137
+ bootstrap_enrollment_id=bootstrap_enrollment_id)
138
+ return encoded
@@ -0,0 +1,250 @@
1
+ # SPDX-License-Identifier: MIT OR Apache-2.0
2
+ """Trusted install-reference issuance and read-only current-head observation.
3
+
4
+ References are trusted host configuration, never client-supplied capabilities.
5
+ Observing a head does not admit a data operation or freeze native role catalogs.
6
+ """
7
+ from __future__ import annotations
8
+
9
+ import asyncio
10
+ import hashlib
11
+ import json
12
+ import re
13
+ from concurrent.futures import ThreadPoolExecutor
14
+ from typing import Any, cast
15
+
16
+ from .catalog import CatalogError, _q, _q_bound
17
+ from .head_view import HEAD, _head_oid, _head_oid_steps, _head_shape, _head_shape_steps
18
+ from .ledger_schema import _history_shape, _history_shape_steps
19
+ from .outcome_schema import _outcome_shape, _outcome_shape_steps
20
+ from .probe import _Query, _run
21
+ from .witness import _json_bytes
22
+
23
+ _REFERENCE_KEYS = {'version','bundleDigest','sourceDigest','configurationDigest',
24
+ 'generation','headDigest','planDigest','headRelationOid','headShape',
25
+ 'nativeWitness','historyShape','referenceDigest'}
26
+ _APPROVAL_REFERENCE_KEYS = {'approvalProfile', 'approvalPlanDigest', 'approvalShape'}
27
+ _MAX_REFERENCE_BYTES = 16*1024*1024
28
+
29
+
30
+ def _normalized(value: Any) -> Any:
31
+ raw = _json_bytes(value)
32
+ if len(raw) > _MAX_REFERENCE_BYTES:
33
+ raise CatalogError('installation-reference-capacity')
34
+ return json.loads(raw)
35
+
36
+
37
+ def _issue_reference(connection: Any, source: dict[str, Any], entry: dict[str, Any]) -> dict[str, Any]:
38
+ """Call only after full original-source native verification under install lock."""
39
+ schema = source['configuration']['schema']
40
+ reference = _normalized({'version':'umf.table-installation/0.1',
41
+ 'bundleDigest':source['bundleDigest'],'sourceDigest':source['sourceDigest'],
42
+ 'configurationDigest':source['configurationDigest'],'generation':entry['position'],
43
+ 'headDigest':entry['entryDigest'],'planDigest':entry['plan']['digest'],
44
+ 'headRelationOid':_head_oid(connection,schema),'headShape':_head_shape(connection,schema),
45
+ 'historyShape':_history_shape(connection,schema),
46
+ 'nativeWitness':entry['witness']})
47
+ outcome_shape=_outcome_shape(connection,schema)
48
+ if outcome_shape is not None:
49
+ reference.update(version='umf.table-installation/0.2',outcomeShape=_normalized(outcome_shape))
50
+ if entry['plan'].get('version') in ('umf.table-migration/0.3','umf.table-migration/0.4','umf.table-migration/0.5'):
51
+ from .approval import APPROVAL_PROFILE, _approval_shape
52
+
53
+ if entry['plan'].get('approvalProfile') != APPROVAL_PROFILE or entry['plan']['digest'] != reference['planDigest']:
54
+ raise CatalogError('installation-reference-mismatch')
55
+ reference.update(version='umf.table-installation/0.3',
56
+ approvalProfile=APPROVAL_PROFILE,
57
+ approvalPlanDigest=entry['plan']['digest'],
58
+ approvalShape=_normalized(_approval_shape(connection, source)))
59
+ reference['referenceDigest'] = hashlib.sha256(_json_bytes(reference)).hexdigest()
60
+ return reference
61
+
62
+
63
+ def _checked_reference(reference: dict[str, object], source: dict[str, Any]) -> dict[str, Any]:
64
+ if type(reference) is not dict:
65
+ raise CatalogError('installation-reference-mismatch')
66
+ version = reference.get('version')
67
+ keys = (_REFERENCE_KEYS | {'outcomeShape'} if version == 'umf.table-installation/0.2'
68
+ else _REFERENCE_KEYS | {'outcomeShape'} | _APPROVAL_REFERENCE_KEYS
69
+ if version == 'umf.table-installation/0.3'
70
+ else _REFERENCE_KEYS)
71
+ if set(reference) != keys:
72
+ raise CatalogError('installation-reference-mismatch')
73
+ checked = _normalized(reference)
74
+ digest = checked.pop('referenceDigest')
75
+ if (checked['version'] not in ('umf.table-installation/0.1','umf.table-installation/0.2','umf.table-installation/0.3')
76
+ or checked['version']=='umf.table-installation/0.2' and type(checked['outcomeShape']) is not dict
77
+ or checked['version']=='umf.table-installation/0.3' and (
78
+ checked['approvalProfile'] != {'version':'umf.table-migration-approval/0.1',
79
+ 'relation':'umf_lifecycle_approvals','ownerOnly':True}
80
+ or checked['approvalPlanDigest'] != checked['planDigest']
81
+ or type(checked['approvalShape']) is not dict
82
+ or type(checked.get('outcomeShape')) is not dict)
83
+ or digest != hashlib.sha256(_json_bytes(checked)).hexdigest()
84
+ or any(checked[key] != source[key] for key in ('bundleDigest','sourceDigest','configurationDigest'))
85
+ or type(checked['generation']) is not int or not 1 <= checked['generation'] <= 128
86
+ or type(checked['headRelationOid']) is not int or not 1 <= checked['headRelationOid'] < 2**32
87
+ or any(type(checked[k]) is not str or not re.fullmatch('[a-f0-9]{64}',checked[k]) for k in ('headDigest','planDigest'))
88
+ or type(checked['headShape']) is not dict or type(checked['nativeWitness']) is not dict
89
+ or type(checked['historyShape']) is not dict):
90
+ raise CatalogError('installation-reference-mismatch')
91
+ checked['referenceDigest'] = digest
92
+ return cast(dict[str, Any],checked)
93
+
94
+
95
+ class TableHeadProbe:
96
+ """Prepared library-owned metadata checks; not a data admission capability.
97
+
98
+ Construct with prepare_table_head. Source and expected native metadata are
99
+ copied by their original verifiers. Drivers only schedule its fixed queries.
100
+ """
101
+ __slots__ = ('_expected', '_lock_timeout_ms', '_source', '_statement_timeout_ms')
102
+
103
+ def __init__(self, source: dict[str, Any], expected: dict[str, Any], statement_timeout_ms: int, lock_timeout_ms: int):
104
+ self._source,self._expected = source,expected
105
+ self._statement_timeout_ms,self._lock_timeout_ms = statement_timeout_ms,lock_timeout_ms
106
+
107
+ @property
108
+ def schema(self) -> str:
109
+ return self._source['configuration']['schema']
110
+
111
+ def steps(self) -> Any:
112
+ return _head_steps(self._source,self._expected,self._statement_timeout_ms,self._lock_timeout_ms)
113
+
114
+
115
+ def prepare_table_head(bundle: dict[str, object], reference: dict[str, object], *,
116
+ statement_timeout_ms: int = 30_000, lock_timeout_ms: int = 5_000) -> TableHeadProbe:
117
+ """Reverify original source and trusted reference before any lease or query.
118
+
119
+ The reference is trusted deployment configuration, never wire authority.
120
+ No connection, executable callback or SQL text is accepted from a document.
121
+ """
122
+ for timeout in (statement_timeout_ms,lock_timeout_ms):
123
+ if type(timeout) is not int or not 1 <= timeout <= 300_000:
124
+ raise ValueError('head timeouts must be 1..300000 milliseconds')
125
+ try:
126
+ asyncio.get_running_loop()
127
+ except RuntimeError:
128
+ source = _original_source(bundle)
129
+ else:
130
+ # A synchronous host call remains synchronous inside a running loop.
131
+ # Only bounded CPU verification moves to a worker, never the connection;
132
+ # no coroutine is run or scheduled by this synchronous entry point.
133
+ with ThreadPoolExecutor(max_workers=1) as worker:
134
+ source = worker.submit(_original_source,bundle).result()
135
+ return TableHeadProbe(source,_checked_reference(reference,source),statement_timeout_ms,lock_timeout_ms)
136
+
137
+
138
+ def _original_source(bundle: dict[str, object]) -> dict[str, Any]:
139
+ from umf_codegen import verify_table_deployment
140
+ try:
141
+ return cast(dict[str, Any],verify_table_deployment(bundle))
142
+ except (ValueError,TypeError):
143
+ raise CatalogError('source-mismatch') from None
144
+
145
+
146
+ def read_table_head(connection: Any, bundle: dict[str, object], reference: dict[str, object], *,
147
+ statement_timeout_ms: int = 30_000, lock_timeout_ms: int = 5_000) -> dict[str, object]:
148
+ """Psycopg3 caller-transaction observer; never commit or admit data methods.
149
+
150
+ Ordinary adapters schedule the same prepared checks through per-call leases.
151
+ The shared lifecycle lock lasts until the caller ends this transaction.
152
+ """
153
+ from psycopg import Error as NativeError
154
+
155
+ probe = prepare_table_head(bundle,reference,statement_timeout_ms=statement_timeout_ms,lock_timeout_ms=lock_timeout_ms)
156
+ if int(connection.info.transaction_status) != 2:
157
+ raise CatalogError('transaction-required')
158
+ try:
159
+ with connection.transaction():
160
+ return _run(connection,probe.steps())
161
+ except CatalogError:
162
+ raise
163
+ except (NativeError,ValueError,TypeError,KeyError,IndexError):
164
+ raise CatalogError('head-observation-failed') from None
165
+
166
+
167
+ def _head_steps(source, expected, statement_timeout_ms, lock_timeout_ms):
168
+ schema = source['configuration']['schema']
169
+ previous = (yield _Query('one', "SELECT pg_catalog.current_setting('statement_timeout'),pg_catalog.current_setting('lock_timeout')", ()))
170
+ yield _Query('one', "SELECT pg_catalog.set_config('statement_timeout',%s,true),pg_catalog.set_config('lock_timeout',%s,true)", (str(statement_timeout_ms), str(lock_timeout_ms)))
171
+ state = (yield _Query('one', "SELECT current_user,pg_catalog.current_schemas(false),\npg_catalog.current_setting('server_version_num')::pg_catalog.int4,\npg_catalog.current_setting('row_security'),pg_catalog.current_setting('session_replication_role'),\npg_catalog.current_setting('server_encoding'),pg_catalog.current_setting('transaction_isolation')", ()))
172
+ if state[1] != ['pg_catalog'] or state[2] // 10000 != 18 or tuple(state[3:]) != ('on', 'origin', 'UTF8', 'read committed'):
173
+ raise CatalogError('head-context-mismatch')
174
+ lock = int.from_bytes(hashlib.sha256(('umf.table-lifecycle/0.1\x00' + schema).encode()).digest()[:8], 'big', signed=True)
175
+ yield _Query('one', 'SELECT pg_catalog.pg_advisory_xact_lock_shared(%s)', (lock,))
176
+ if (yield from _head_oid_steps(schema)) != expected['headRelationOid'] or _normalized((yield from _head_shape_steps(schema))) != expected['headShape']:
177
+ raise CatalogError('head-view-catalog-mismatch')
178
+ if _normalized((yield from _history_shape_steps(schema))) != expected['historyShape']:
179
+ raise CatalogError('history-catalog-mismatch')
180
+ if _normalized((yield from _outcome_shape_steps(schema))) != expected.get('outcomeShape'):
181
+ raise CatalogError('outcome-catalog-mismatch')
182
+ if expected['version'] == 'umf.table-installation/0.3':
183
+ from .approval import _approval_shape_steps
184
+
185
+ if _normalized((yield from _approval_shape_steps(schema))) != expected['approvalShape']:
186
+ raise CatalogError('approval-catalog-mismatch')
187
+ yield _Query('execute', 'LOCK TABLE ' + _q(schema) + '.' + _q(HEAD) + ' IN ACCESS SHARE MODE', ())
188
+ location = (yield _Query('one', 'SELECT d.oid,d.datname,n.oid,n.nspowner\nFROM pg_catalog.pg_database d,pg_catalog.pg_namespace n\nWHERE d.datname=pg_catalog.current_database() AND n.nspname=%s', (schema,)))
189
+ witness = expected['nativeWitness']
190
+ if location is None or list(location[:2]) != witness.get('database') or list(location[2:]) != witness.get('schema') or (state[2] != witness.get('serverVersion')):
191
+ raise CatalogError('installation-location-mismatch')
192
+ if (yield from _head_oid_steps(schema)) != expected['headRelationOid'] or _normalized((yield from _head_shape_steps(schema))) != expected['headShape']:
193
+ raise CatalogError('head-view-catalog-mismatch')
194
+ if _normalized((yield from _history_shape_steps(schema))) != expected['historyShape']:
195
+ raise CatalogError('history-catalog-mismatch')
196
+ if _normalized((yield from _outcome_shape_steps(schema))) != expected.get('outcomeShape'):
197
+ raise CatalogError('outcome-catalog-mismatch')
198
+ if expected['version'] == 'umf.table-installation/0.3':
199
+ from .approval import _approval_shape_steps
200
+
201
+ if _normalized((yield from _approval_shape_steps(schema))) != expected['approvalShape']:
202
+ raise CatalogError('approval-catalog-mismatch')
203
+ relation = _q(schema) + '.' + _q(HEAD)
204
+ row = (yield _Query('one', 'SELECT generation,head_digest,plan_digest,bundle_digest,source_digest,\nconfiguration_digest,pg_catalog.octet_length(native_witness::pg_catalog.text) FROM ' + relation, ()))
205
+ if row is None or tuple(row[:6]) != tuple(expected[k] for k in ('generation', 'headDigest', 'planDigest', 'bundleDigest', 'sourceDigest', 'configurationDigest')):
206
+ raise CatalogError('installed-generation-mismatch')
207
+ if type(row[6]) is not int or not 0 < row[6] <= _MAX_REFERENCE_BYTES:
208
+ raise CatalogError('installation-reference-capacity')
209
+ if (yield _Query('one', 'SELECT native_witness FROM ' + relation, ()))[0] != expected['nativeWitness']:
210
+ raise CatalogError('installed-generation-mismatch')
211
+ yield _Query('one', "SELECT pg_catalog.set_config('statement_timeout',%s,true),pg_catalog.set_config('lock_timeout',%s,true)", tuple(previous))
212
+ return {'bundleDigest': source['bundleDigest'], 'headDigest': expected['headDigest'], 'generation': expected['generation'], 'referenceDigest': expected['referenceDigest'], 'observedPrincipal': state[0], 'lifecycleAdmission': False}
213
+
214
+
215
+ def _operation_head_steps(source, expected, principal):
216
+ """Take the short operation observation under the shared lifecycle lock.
217
+
218
+ The install reference is already verified and owned by this prepared probe.
219
+ This deliberately checks only immutable head/location pins and session
220
+ context; diagnostic ``steps()`` remains the full catalog auditor.
221
+ """
222
+ schema = source['configuration']['schema']
223
+ lock = int.from_bytes(hashlib.sha256(('umf.table-lifecycle/0.1\x00' + schema).encode()).digest()[:8], 'big', signed=True)
224
+ yield _Query('one', 'SELECT pg_catalog.pg_advisory_xact_lock_shared(%s)', (lock,))
225
+ relation = _q_bound(schema) + '.' + _q_bound(HEAD)
226
+ row = yield _Query('one', """SELECT current_user,pg_catalog.current_schemas(false),
227
+ pg_catalog.current_setting('server_version_num')::pg_catalog.int4,
228
+ pg_catalog.current_setting('row_security'),pg_catalog.current_setting('session_replication_role'),
229
+ pg_catalog.current_setting('server_encoding'),pg_catalog.current_setting('transaction_isolation'),
230
+ d.oid,d.datname,n.oid,n.nspowner,c.oid,
231
+ h.generation,h.head_digest,h.plan_digest
232
+ FROM pg_catalog.pg_database d
233
+ JOIN pg_catalog.pg_namespace n ON n.nspname=%s
234
+ JOIN pg_catalog.pg_class c ON c.relnamespace=n.oid AND c.relname=%s
235
+ JOIN """ + relation + """ h ON TRUE
236
+ WHERE d.datname=pg_catalog.current_database()""", (schema, HEAD))
237
+ if row is None:
238
+ raise CatalogError('installed-generation-mismatch')
239
+ if (row[0] != principal or row[1] != ['pg_catalog'] or row[2] // 10000 != 18
240
+ or tuple(row[3:7]) != ('on', 'origin', 'UTF8', 'read committed')):
241
+ raise CatalogError('head-context-mismatch' if row[0] == principal else 'principal-mismatch')
242
+ witness = expected['nativeWitness']
243
+ if (list(row[7:9]) != witness.get('database') or list(row[9:11]) != witness.get('schema')
244
+ or row[11] != expected['headRelationOid'] or row[2] != witness.get('serverVersion')):
245
+ raise CatalogError('installation-location-mismatch')
246
+ if tuple(row[12:15]) != tuple(expected[k] for k in ('generation', 'headDigest', 'planDigest')):
247
+ raise CatalogError('installed-generation-mismatch')
248
+ return {'bundleDigest': source['bundleDigest'], 'headDigest': expected['headDigest'],
249
+ 'generation': expected['generation'], 'referenceDigest': expected['referenceDigest'],
250
+ 'observedPrincipal': row[0], 'lifecycleAdmission': False}
@@ -0,0 +1,81 @@
1
+ # SPDX-License-Identifier: MIT OR Apache-2.0
2
+ """Fixed metadata projection. Original plans and seed contents stay private."""
3
+ from __future__ import annotations
4
+
5
+ from typing import Any
6
+ from uuid import uuid4
7
+
8
+ from .catalog import _COLUMNS, CatalogError, _all, _execute, _one, _q
9
+ from .ledger_schema import HISTORY
10
+ from .probe import _Query, _run
11
+
12
+ HEAD = 'umf_lifecycle_head'
13
+
14
+
15
+ def _create_head_view(connection: Any, source: dict[str, Any], name: str = HEAD) -> None:
16
+ cfg = source['configuration']
17
+ relation = _q(cfg['schema'])+'.'+_q(name)
18
+ # No user function, unqualified operator, original plan or seed projection.
19
+ _execute(connection, 'CREATE VIEW '+relation+''' WITH (security_barrier=true,security_invoker=false) AS
20
+ SELECT position AS generation,entry_digest AS head_digest,plan_digest,
21
+ pg_catalog.jsonb_extract_path_text(payload,'plan','toBundleDigest') AS bundle_digest,
22
+ pg_catalog.jsonb_extract_path_text(payload,'plan','next','sourceDigest') AS source_digest,
23
+ pg_catalog.jsonb_extract_path_text(payload,'plan','next','configurationDigest') AS configuration_digest,
24
+ pg_catalog.jsonb_extract_path(payload,'witness') AS native_witness
25
+ FROM '''+_q(cfg['schema'])+'.'+_q(HISTORY)+' ORDER BY position DESC LIMIT 1')
26
+ _execute(connection,'REVOKE ALL ON TABLE '+relation+' FROM PUBLIC')
27
+ _execute(connection,'GRANT SELECT ON TABLE '+relation+' TO '+_q(cfg['personRole'])+', '+_q(cfg['batchRole']))
28
+
29
+
30
+ def _head_oid(connection: Any, schema: str, name: str = HEAD) -> int | None:
31
+ return _run(connection, _head_oid_steps(schema,name))
32
+
33
+
34
+ def _head_oid_steps(schema: str, name: str=HEAD):
35
+ row = (yield _Query('one', 'SELECT c.oid FROM pg_catalog.pg_class c\nJOIN pg_catalog.pg_namespace n ON n.oid=c.relnamespace WHERE n.nspname=%s AND c.relname=%s', (schema, name)))
36
+ return None if row is None else row[0]
37
+
38
+
39
+ def _head_shape(connection: Any, schema: str, name: str = HEAD) -> dict[str, Any] | None:
40
+ return _run(connection, _head_shape_steps(schema,name))
41
+
42
+
43
+ def _head_shape_steps(schema: str, name: str=HEAD):
44
+ oid = (yield from _head_oid_steps(schema, name))
45
+ if oid is None:
46
+ return None
47
+ state = (yield _Query('one', 'SELECT c.relkind,c.relpersistence,c.relowner,c.relrowsecurity,\nc.relforcerowsecurity,c.relispartition,c.relhassubclass,c.relhasrules,c.relreplident,\nARRAY(SELECT opt FROM pg_catalog.unnest(c.reloptions) opt ORDER BY opt),\nEXISTS(SELECT FROM pg_catalog.pg_trigger t WHERE t.tgrelid=c.oid),\nEXISTS(SELECT FROM pg_catalog.pg_inherits i WHERE i.inhrelid=c.oid OR i.inhparent=c.oid),\nEXISTS(SELECT FROM pg_catalog.pg_policy p WHERE p.polrelid=c.oid),\nEXISTS(SELECT FROM pg_catalog.pg_constraint k WHERE k.conrelid=c.oid)\nFROM pg_catalog.pg_class c WHERE c.oid=%s', (oid,)))
48
+ if state is None or state[0] != 'v':
49
+ raise CatalogError('head-view-catalog-mismatch')
50
+ rules = (yield _Query('all', 'SELECT rulename,ev_type,is_instead,ev_enabled\nFROM pg_catalog.pg_rewrite WHERE ev_class=%s ORDER BY rulename', (oid,)))
51
+ dependencies = (yield _Query('all', "SELECT d.refclassid,\nCASE WHEN d.refclassid='pg_catalog.pg_class'::pg_catalog.regclass AND d.refobjid=%s\nTHEN 'self' ELSE d.refobjid::pg_catalog.text END,d.refobjsubid,d.deptype\nFROM pg_catalog.pg_depend d JOIN pg_catalog.pg_rewrite r ON r.oid=d.objid\nWHERE d.classid='pg_catalog.pg_rewrite'::pg_catalog.regclass AND r.ev_class=%s\nORDER BY 1,2,3,4", (oid, oid)))
52
+ acl = (yield _Query('all', "SELECT grantor,grantee,privilege_type,is_grantable\nFROM pg_catalog.pg_class c,LATERAL pg_catalog.aclexplode(COALESCE(c.relacl,pg_catalog.acldefault('r',c.relowner)))\nWHERE c.oid=%s ORDER BY 1,2,3,4", (oid,)))
53
+ column_acl = (yield _Query('all', 'SELECT a.attname,x.grantor,x.grantee,x.privilege_type,x.is_grantable\nFROM pg_catalog.pg_attribute a,LATERAL pg_catalog.aclexplode(a.attacl) x\nWHERE a.attrelid=%s ORDER BY 1,2,3,4,5', (oid,)))
54
+ return {'state': state, 'columns': (yield _Query('all', _COLUMNS, (schema, name))), 'rules': rules, 'definition': (yield _Query('one', 'SELECT pg_catalog.pg_get_viewdef(%s::pg_catalog.oid,true)', (oid,)))[0], 'dependencies': dependencies, 'acl': acl, 'columnAcl': column_acl}
55
+
56
+
57
+ def _verify_head_view(connection: Any, source: dict[str, Any]) -> bool:
58
+ """Administrative source proof, not a first-observed definition fingerprint."""
59
+ cfg = source['configuration']
60
+ schema = cfg['schema']
61
+ before = _head_shape(connection,schema)
62
+ if before is None:
63
+ return False
64
+ actual = before
65
+ owner_id = _one(connection,'SELECT oid FROM pg_catalog.pg_roles WHERE rolname=%s',(cfg['ownerRole'],))[0]
66
+ expected_acl = _all(connection,'''SELECT grantor,grantee,privilege_type,is_grantable
67
+ FROM pg_catalog.aclexplode(pg_catalog.acldefault('r',%s::pg_catalog.oid))''',(owner_id,))
68
+ for role in (cfg['personRole'],cfg['batchRole']):
69
+ role_id = _one(connection,'SELECT oid FROM pg_catalog.pg_roles WHERE rolname=%s',(role,))[0]
70
+ expected_acl.append((owner_id,role_id,'SELECT',False))
71
+ if actual['acl'] != sorted(expected_acl) or actual['columnAcl']:
72
+ raise CatalogError('head-view-privilege-mismatch')
73
+ temporary = 'umf_verify_'+uuid4().hex
74
+ _create_head_view(connection,source,temporary)
75
+ if actual != _head_shape(connection,schema,temporary):
76
+ raise CatalogError('head-view-catalog-mismatch')
77
+ _execute(connection,'LOCK TABLE '+_q(schema)+'.'+_q(HEAD)+' IN ACCESS SHARE MODE')
78
+ if actual != _head_shape(connection,schema):
79
+ raise CatalogError('head-view-catalog-mismatch')
80
+ _execute(connection,'DROP VIEW '+_q(schema)+'.'+_q(temporary))
81
+ return True