File size: 13,061 Bytes
870b85a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
"""Cross-run memory of asset-intrinsic native activation rejections; never scene facts.

Only installation_preparation_rejected verdicts whose reason is decided by the
pinned source attribute release row alone are kept. The early installation
check (early_installation_precheck.check_before_preparation) consults the
entity only to decide whether an installation category applies; the verdict
itself reads asset_id, source/runtime bytes, canonical frame and the release
row. Parent placement, wall anchors, rooms and siblings are never consulted.

A record is keyed by asset identity (asset_id, role, raw retrieval record,
explicit source pins), the attribute-release specification bytes and the bytes
of every module on the verdict path. Any change is a different key. A lookup
also re-verifies the delivery, all referenced records and current source/runtime bytes.
Unreadable, malformed or mismatched records are misses: activation then runs
exactly as before. Set RHG_ACTIVATION_NEGATIVE_CACHE=0 to disable.
"""
from pathlib import Path
import hashlib
import json
import os
import time
import uuid

SCHEMA = 'rhg.persistent_activation_rejection.v1'
REASON = 'persistent_prior_activation_rejection'
PREFIX = 'installation_preparation_rejected: '
# installation_contracts._source_installation returns these only after one
# exact release row matched; they read that row's installation field alone.
CACHEABLE_REASONS = frozenset({'source_installation_type_unverified'})
VISUAL_MOUNT = ('installation_type_', '_unverified_visual_mount')
TREE_MODULES = ('native_asset_activation.py', 'early_installation_precheck.py',
                'installation_contracts.py', 'activation_rejection_cache.py')
NATIVE_MODULES = ('source_attribute_consumer.py', 'style_attribute_consumer.py',
                  'annotation_retrieval.py', 'stage_checkpoint.py')
_BASIS_FIELDS = ('release_delivery', 'release_delivery_sha256', 'records_sha256',
                 'source_record_id', 'source_sha256', 'runtime_sha256', 'canonical_transform')
_HASHES = {}


def configure(runtime):
    """Persist explicit policy before recovery clears inherited RHG_* variables."""
    runtime.setdefault('activation_negative_cache',
        os.environ.get('RHG_ACTIVATION_NEGATIVE_CACHE', '1') != '0')


def enabled(runtime):
    policy = runtime.get('activation_negative_cache',
        os.environ.get('RHG_ACTIVATION_NEGATIVE_CACHE', '1') != '0')
    return bool(runtime.get('artifact_cache_root')) and policy is True


def cacheable_reason(reason):
    if not isinstance(reason, str):
        return False
    if reason in CACHEABLE_REASONS:
        return True
    head, tail = VISUAL_MOUNT
    return reason.startswith(head) and reason.endswith(tail) and len(reason) > len(head) + len(tail)


def _sha(path):
    path = Path(path).resolve()
    stat = path.stat()
    marker = (str(path), stat.st_size, stat.st_mtime_ns, stat.st_ctime_ns)
    if marker not in _HASHES:
        digest = hashlib.sha256()
        with path.open('rb') as stream:
            for block in iter(lambda: stream.read(4 * 1024 * 1024), b''):
                digest.update(block)
        _HASHES[marker] = digest.hexdigest()
    return _HASHES[marker]


def _fingerprint(value):
    return hashlib.sha256(json.dumps(value, sort_keys=True, separators=(',', ':'),
                                     allow_nan=False).encode()).hexdigest()


def code_signature(runtime):
    """Bytes of every module deciding the verdict; None disables the cache."""
    try:
        from native_asset_activation import _source_root
        here = Path(__file__).resolve().parent
        native = _source_root(runtime)/'scripts/internal/scene_generation/real_assets'
        values = {name: _sha(here/name) for name in TREE_MODULES}
        values.update({'native/' + name: _sha(native/name) for name in NATIVE_MODULES})
        return _fingerprint(values)
    except Exception:
        return None


def release_identity(runtime):
    spec = runtime.get('attribute_release')
    try:
        if isinstance(spec, (str, Path)):
            return {'path': str(Path(spec).resolve()), 'sha256': _sha(spec)}
        if isinstance(spec, dict) and spec:
            return {'inline_sha256': _fingerprint(spec)}
    except Exception:
        return None
    return None


def _installation_entity(entity):
    try:
        from installation_contracts import INSTALLATIONS, _category
        return isinstance(entity, dict) and _category(entity) in INSTALLATIONS
    except Exception:
        return False


def cache_key(runtime, entry, signature=None):
    """Key of an activation input row (dynamic_selection pending entry), or None."""
    if not entry.get('asset_id') or not isinstance(entry.get('raw_record_sha256'), str):
        return None
    signature = signature or code_signature(runtime)
    release = release_identity(runtime)
    if signature is None or release is None:
        return None
    return _fingerprint({'schema': SCHEMA, 'asset_id': entry['asset_id'], 'role': entry.get('role'),
        'raw_record_sha256': entry['raw_record_sha256'],
        'explicit_source_pins': entry.get('explicit_source_pins') or {},
        'source_release_record_id': entry.get('source_release_record_id'),
        'activation_requirements': entry.get('activation_requirements') or {},
        'max_published_variants': runtime.get('activation_max_published_variants', 16),
        'attribute_release': release, 'code_signature': signature,
        # The verdict exists only for entities inside the installation gate.
        'installation_gate': True})


def _directory(runtime):
    return Path(runtime['artifact_cache_root']).resolve()/'activation_rejections'/'v1'


def _digest(record):
    return _fingerprint({k: v for k, v in record.items() if k != 'record_sha256'})


def _raw_paths(entry):
    raw = json.loads(entry['raw_record_json'])
    if hashlib.sha256(entry['raw_record_json'].encode('utf-8')).hexdigest() != entry['raw_record_sha256']:
        raise ValueError('raw_record_sha256_mismatch')
    source = raw.get('canonical_path')
    return source, raw.get('runtime_path') or source


def _release_record_hashes(delivery, visited=None):
    """Verify every hash-pinned member and payload; do not trust delivery alone.

    A release set can gain an ambiguous source match if a referenced records
    file changes. Verify all members, while stat-keyed SHA memoization prevents
    hashing the large immutable records file again for each candidate/round.
    """
    visited = set() if visited is None else visited
    path = Path(delivery).resolve()
    if path in visited or len(visited) >= 64:
        raise ValueError('cyclic_or_oversized_attribute_release')
    visited.add(path)
    value = json.loads(path.read_text())
    if value.get('schema') in {'rhg.attribute_release_set.v1', 'rhg.attribute_release_catalog.v1'}:
        hashes = []
        hashes.extend(_member_record_hashes(value['releases'], visited))
        for patch in value.get('functional_patches', []):
            if _sha(patch['path']) != patch['sha256']:
                raise ValueError('attribute_functional_patch_changed')
        if not hashes:
            raise ValueError('empty_attribute_release_set')
        return hashes
    ref = value['artifacts']['records.jsonl']
    if _sha(ref['uri']) != ref['sha256']:
        raise ValueError('attribute_records_changed')
    return [ref['sha256']]


def _member_record_hashes(members, visited):
    hashes = []
    for member in members:
        path = member.get('delivery') or member['delivery_uri']
        expected = member.get('sha256') or member['delivery_sha256']
        if _sha(path) != expected:
            raise ValueError('attribute_delivery_member_changed')
        hashes.extend(_release_record_hashes(path, visited))
    return hashes


def _runtime_record_hashes(runtime):
    specification = runtime['attribute_release']
    if isinstance(specification, (str, Path)):
        return _release_record_hashes(specification)
    members = specification['releases'] if 'releases' in specification else [specification]
    return _member_record_hashes(members, set())


def _inputs_current(runtime_config, record, entry):
    basis = record['metadata_basis']
    if _sha(basis['release_delivery']) != basis['release_delivery_sha256']:
        return False
    if basis['records_sha256'] not in _release_record_hashes(basis['release_delivery']):
        return False
    # The activation worker first validates the complete runtime release set.
    # Do not hide an invalid other member merely because the chosen member is intact.
    if basis['records_sha256'] not in _runtime_record_hashes(runtime_config):
        return False
    source, runtime = _raw_paths(entry)
    return bool(source) and _sha(source) == basis['source_sha256'] and _sha(runtime) == basis['runtime_sha256']


def lookup(runtime, entry, signature=None):
    """Validated prior rejection for this exact input, else None. Never raises."""
    try:
        if not enabled(runtime) or not _installation_entity(entry.get('activation_entity')):
            return None
        key = cache_key(runtime, entry, signature)
        if key is None:
            return None
        path = _directory(runtime)/(key + '.json')
        record = json.loads(path.read_text())
        if (not isinstance(record, dict) or record.get('schema') != SCHEMA or record.get('key') != key
                or record.get('record_sha256') != _digest(record) or record.get('asset_id') != entry['asset_id']
                or not cacheable_reason(record.get('reason')) or record.get('error') != PREFIX + record['reason']
                or not isinstance(record.get('metadata_basis'), dict)
                or any(record['metadata_basis'].get(k) in (None, '') for k in _BASIS_FIELDS)):
            return None
        if not _inputs_current(runtime, record, entry):
            return None
        return dict(record, cache_record_path=str(path))
    except Exception:
        return None


def rejection_from_activation(asset):
    """Return (reason, basis) when an activation result may be persisted."""
    if not isinstance(asset, dict) or asset.get('activation_status', asset.get('status')) != 'failed':
        return None
    if asset.get('error_scope') == 'infrastructure' or asset.get('error_type') != 'ValueError':
        return None
    error = asset.get('error')
    check = asset.get('installation_preparation_precheck')
    if not isinstance(error, str) or not error.startswith(PREFIX) or not isinstance(check, dict):
        return None
    reason = error[len(PREFIX):]
    basis = check.get('metadata_basis')
    if (not cacheable_reason(reason) or check.get('reason') != reason or check.get('asset_id') != asset.get('asset_id')
            or check.get('source_installation') is not None or not isinstance(basis, dict)
            or basis.get('physical_qualified') is not False
            or any(basis.get(k) in (None, '') for k in _BASIS_FIELDS)):
        return None
    return reason, basis


def record(runtime, entry, asset, origin, signature=None):
    """Persist a qualifying rejection atomically; returns the record path or None."""
    try:
        if not enabled(runtime) or not _installation_entity(entry.get('activation_entity')):
            return None
        if not isinstance(asset, dict) or asset.get('asset_id') != entry.get('asset_id'):
            return None
        if asset.get('entity_id') not in (None, entry.get('entity_id')):
            return None
        verdict = rejection_from_activation(asset)
        if verdict is None:
            return None
        reason, basis = verdict
        key = cache_key(runtime, entry, signature)
        if key is None:
            return None
        source, runtime_path = _raw_paths(entry)
        # Persist only when the bytes activation judged are the current bytes.
        if not source or _sha(source) != basis['source_sha256'] or _sha(runtime_path) != basis['runtime_sha256']:
            return None
        if not _inputs_current(runtime, {'metadata_basis': basis}, entry):
            return None
        value = {'schema': SCHEMA, 'key': key, 'asset_id': entry['asset_id'], 'role': entry.get('role'),
                 'reason': reason, 'error': asset['error'], 'error_type': asset.get('error_type'),
                 'metadata_basis': basis, 'scope': 'asset_source_release_row_only; not_room_parent_or_layout',
                 'origin': dict(origin, recorded_at=time.time())}
        value['record_sha256'] = _digest(value)
        directory = _directory(runtime)
        directory.mkdir(parents=True, exist_ok=True)
        target = directory/(key + '.json')
        temporary = directory/('.' + key + '.' + uuid.uuid4().hex + '.tmp')
        try:
            temporary.write_text(json.dumps(value, sort_keys=True, ensure_ascii=False) + '\n')
            os.replace(temporary, target)
        finally:
            if temporary.exists():
                temporary.unlink()
        return str(target)
    except Exception:
        return None