File size: 9,764 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
"""Verify native pool eligibility before using its effective output domain."""
import copy
import hashlib
import json
from pathlib import Path
import sys

if __package__:
    from .native_contract import digest, load_pools
else:
    from native_contract import digest, load_pools


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


def read_bound(path, inputs):
    path = Path(path).resolve()
    sha = digest(path)
    if str(path) in inputs and inputs[str(path)] != sha:
        raise ValueError('Previously bound input changed: ' + str(path))
    value = json.loads(path.read_text())
    json.dumps(value, allow_nan=False)
    if digest(path) != sha:
        raise ValueError('Effective contract input changed while reading')
    inputs[str(path)] = sha
    return value


def request_enrichments(request, runtime, inputs):
    """Allow only the pinned native loader/compiler's documented enrichments."""
    runtime = runtime or {}
    expected = copy.deepcopy(request)
    expected.setdefault('support_region_policy', 'mesh_union')
    expected.setdefault('floor_cover_policy', 'measured_support')
    if runtime.get('candidate_selection_policy') == 'eligible_role_pool':
        expected.setdefault('collision_admission_policy', 'disabled')
    search = expected.setdefault('search', {})
    for key, value in dict(grid_step_m=.4, max_nodes_per_room=80000,
            max_seconds_per_room=180, critical_boundary_poses=True,
            chair_tangent_offsets_m=[0, -.1, .1, -.2, .2, -.3, .3],
            rug_center_offsets_m=[0, -.1, .1, -.2, .2, -.3, .3]).items():
        search.setdefault(key, value)
    if runtime.get('prepared_support_surfaces'):
        index = read_bound(runtime['prepared_support_surfaces'], inputs)
        if index.get('schema') != 'rhg.prepared_support_surfaces.v1':
            raise ValueError('Unsupported prepared support surface index')
        refs = expected.setdefault('support_surface_feedback', [])
        for ref in index['sources']:
            if ref not in refs:
                refs.append(ref)
    if runtime.get('prepared_floor_body_geometry'):
        path = Path(runtime['prepared_floor_body_geometry']).resolve()
        read_bound(path, inputs)
        expected.setdefault('floor_body_geometry_index', dict(path=str(path), sha256=inputs[str(path)]))
    if 'asset_diversity' not in expected and runtime.get('asset_selection_policy') == 'content_diverse_v1':
        native = Path(__file__).resolve().parent / 'source/scripts/internal/scene_generation/real_assets'
        old_path = sys.path[:]
        try:
            sys.path.insert(0, str(native))
            from bind_fixed_layout import semantic_key
            roles = sorted({semantic_key(entity) for entity in request['entities']})
        finally:
            sys.path[:] = old_path
        expected['asset_diversity'] = dict(roles=roles, seed=int(runtime['seed']),
                                          source='content_diverse_v1_scene_seed')
    return expected


def verified_effective_request(manifest, request, frozen_request, generated_path,
                               pool_paths, inputs, runtime=None):
    """Return (effective request, sealed records, audit), or no-op without evidence.

    Eligibility is produced by the native generator. Its hashes alone do not
    authorize expansion: original constraints and pre-bound pool records must
    independently agree before the outer native byte/size checks can use it.
    """
    frozen_request = Path(frozen_request).resolve()
    root = frozen_request.parent
    effective_path = Path(generated_path).parent / 'eligible_scene_request.json'
    receipt_path = effective_path.with_name('candidate_eligibility_report.json')
    if not effective_path.exists() and not receipt_path.exists():
        return request, None, None
    for path in (effective_path, receipt_path):
        if not path.is_file() or root not in path.resolve().parents:
            raise ValueError('Effective request/receipt must both belong to this attempt')
    if request['mode'] != 'pool':
        raise ValueError('Effective pool expansion is not allowed for a locked request')
    effective = read_bound(effective_path, inputs)
    receipt = read_bound(receipt_path, inputs)
    if (receipt.get('schema') != 'rhg.eligible_candidate_request.v1'
            or receipt.get('passed') is not True
            or Path(receipt.get('input_request', '')).resolve() != frozen_request
            or receipt.get('input_request_sha256') != inputs.get(str(frozen_request))
            or receipt.get('input_request_sha256') != digest(frozen_request)
            or receipt.get('effective_request_sha256') != fingerprint(effective)):
        raise ValueError('Effective eligibility receipt does not bind this frozen request/output')
    if read_bound(frozen_request, inputs) != request:
        raise ValueError('Frozen request differs from the original request')
    bound_pools = {str(Path(path).resolve()): inputs.get(str(Path(path).resolve()))
                   for path in pool_paths}
    reported = receipt.get('prepared_pools', [])
    reported_pools = {str(Path(row['path']).resolve()): row['sha256'] for row in reported}
    if (not bound_pools or None in bound_pools.values()
            or len(reported_pools) != len(reported) or reported_pools != bound_pools):
        raise ValueError('Effective eligibility differs from the pre-bound prepared pools')
    expected = request_enrichments(request, runtime, inputs)
    # Native loading may add defaults, but must never change caller fields.
    for key in set(request) | set(effective):
        if key == 'furniture':
            continue
        if key not in effective:
            raise ValueError('Effective request removed a caller field: ' + key)
        if effective[key] != request.get(key) and effective[key] != expected.get(key):
            raise ValueError('Effective request changed a protected field: ' + key)
        if key not in expected:
            raise ValueError('Effective request added an unauthorized field: ' + key)
    old = {row['entity_id']: row for row in request['furniture']}
    rows = effective['furniture']
    new = {row['entity_id']: row for row in rows}
    audits = receipt.get('entities', [])
    audited = {row['entity_id']: row for row in audits}
    if (len(new) != len(rows) or set(new) != set(old)
            or len(audited) != len(audits) or set(audited) != set(old)
            or set(old) != {row['entity_id'] for row in manifest['entities']}
            or receipt.get('entity_count') != len(old)
            or receipt.get('entity_ids_preserved') is not True
            or receipt.get('task_and_relations_preserved') is not True):
        raise ValueError('Effective eligibility changed the entity inventory')
    ids = {asset for row in rows for asset in row['candidate_asset_ids']}
    candidates, hashes = load_pools(pool_paths, ids)
    if any(inputs.get(path) != sha for path, sha in hashes.items()):
        raise ValueError('Prepared pools/receipts changed since preflight')
    mutable = {'candidate_asset_ids', 'candidate_record_ids',
               'preferred_candidate_record_ids', 'eligible_declared_record_ids'}
    for eid, row in new.items():
        original, audit = old[eid], audited[eid]
        if ({key: value for key, value in row.items() if key not in mutable}
                != {key: value for key, value in original.items() if key not in mutable}):
            raise ValueError('Effective eligibility changed a hard requirement: ' + eid)
        domain, records = row['candidate_asset_ids'], row.get('candidate_record_ids')
        if (not domain or len(set(domain)) != len(domain)
                or not records or len(set(records)) != len(records)
                or audit.get('original_asset_ids') != original['candidate_asset_ids']
                or audit.get('eligible_asset_ids') != domain
                or audit.get('eligible_record_ids') != records):
            raise ValueError('Effective eligibility domains disagree: ' + eid)
        if (original.get('candidate_record_ids')
                and not set(records) <= set(original['candidate_record_ids'])):
            raise ValueError('Effective eligibility widened explicit record pins: ' + eid)
        selected = [candidate for asset in domain for candidate in candidates.get(asset, [])
                    if candidate.get('pool_candidate_key') in records]
        if ({candidate['asset_id'] for candidate in selected} != set(domain)
                or {candidate['pool_candidate_key'] for candidate in selected} != set(records)):
            raise ValueError('Effective eligibility contains an unsealed candidate: ' + eid)
        if any((original.get('record_id') and candidate['pool_candidate_key'] != original['record_id'])
               or (original.get('source_sha256') and candidate.get('asset_sha256') != original['source_sha256'])
               for candidate in selected):
            raise ValueError('Effective eligibility violated a hard record/source pin: ' + eid)
    original_ids = {asset for row in old.values() for asset in row['candidate_asset_ids']}
    audit = dict(schema='rhg.frontier-effective-request-review.v1', passed=True,
                 effective_request=str(effective_path.resolve()),
                 effective_request_sha256=receipt['effective_request_sha256'],
                 input_request_sha256=receipt['input_request_sha256'],
                 prepared_pools=reported, entity_count=len(old),
                 added_asset_ids=sorted(ids - original_ids),
                 scope='effective_domain_provenance_hard_pins_and_sealed_records_only')
    return effective, candidates, audit