File size: 10,910 Bytes
870b85a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3f15e9f
 
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
"""Post-generation furnishing review bound to the actual saved native evidence."""
from __future__ import annotations

from collections import Counter
import copy
import hashlib
import json
from pathlib import Path
import sys


def _read(path):
    return json.loads(Path(path).read_text(encoding='utf-8'))


def _sha(path):
    value = hashlib.sha256()
    with Path(path).open('rb') as stream:
        for chunk in iter(lambda: stream.read(4 * 1024 * 1024), b''):
            value.update(chunk)
    return value.hexdigest()


def _verified_placeholder_preview(case, request):
    placeholders = {entity['entity_id']: entity['procedural_placeholder']
                    for entity in request.get('entities', [])
                    if isinstance(entity.get('procedural_placeholder'), dict)}
    if not placeholders:
        return None
    receipt_path = case / 'procedural_preview_receipt.json'
    receipt = _read(receipt_path)
    if receipt.get('schema') != 'rhg.procedural-placeholder-preview-receipt.v1':
        raise ValueError('Unsupported procedural preview receipt')

    paths = {}
    for key in ('preview_path', 'plan_path', 'report_path'):
        path = Path(receipt[key]).resolve()
        if case not in path.parents or not path.is_file():
            raise ValueError('Procedural preview source is absent or outside this case: ' + key)
        paths[key] = path
    expected_hashes = {
        'preview_path': receipt.get('preview_sha256'),
        'plan_path': receipt.get('plan_sha256'),
        'report_path': receipt.get('report_sha256'),
    }
    if any(_sha(paths[key]) != expected for key, expected in expected_hashes.items()):
        raise ValueError('Procedural preview bytes differ from their receipt')
    plan = _read(paths['plan_path'])
    report = _read(paths['report_path'])
    plan_rows = {row['entity_id']: row for row in plan.get('rows', [])}
    if (plan.get('schema') != 'rhg.procedural-placeholder-plan.v1'
            or set(plan_rows) != set(placeholders)
            or report.get('schema') != 'rhg.procedural-placeholder-preview.v1'
            or report.get('preview_built') is not True
            or report.get('layout_qualified') is not False
            or report.get('preview_sha256') != receipt.get('preview_sha256')
            or report.get('plan_sha256') != receipt.get('plan_sha256')):
        raise ValueError('Procedural preview does not bind the frozen request')
    for entity_id, placeholder in placeholders.items():
        row = plan_rows[entity_id]
        if (row.get('dimensions_m') != placeholder.get('dimensions_m')
                or row.get('tolerance_m') != placeholder.get('tolerance_m')
                or row.get('tolerance_ratio') != placeholder.get('tolerance_ratio')):
            raise ValueError('Procedural preview dimensions differ from request: ' + entity_id)
    return dict(receipt=receipt, paths=paths)


def audit_case(case, output):
    case, output = Path(case).resolve(), Path(output).resolve()
    target = case / 'furnishing_evaluation.json'
    if target.exists():
        raise FileExistsError('Saved furnishing evaluation is immutable')
    if case not in output.parents:
        raise ValueError('Execution output must belong to this case')
    result = _read(output / 'result.json')
    manifest_path = Path(result['generated_manifest']).resolve()
    if output not in manifest_path.parents:
        raise ValueError('Generated manifest is outside this execution')
    geometries = list(output.glob('chain/round_*/attempt_*/geometry/result.json'))
    digest = _sha(manifest_path)
    if result.get('generated_manifest_sha256') != digest:
        raise ValueError('Generated manifest hash differs from the native result')
    matches = [(p, _read(p)) for p in geometries if _read(p).get('manifest_sha256') == digest]
    if len(matches) != 1:
        raise ValueError('Need one source-bound final geometry result')
    geometry_path, geometry = matches[0]
    blend = manifest_path.parent / (manifest_path.parent.name + '.blend')
    if geometry.get('scene_sha256') != _sha(blend):
        raise ValueError('Saved Blender scene differs from measured geometry')
    spec = _read(case / 'approved_scene_spec.json')
    request = _read(case / 'request.json')
    placeholder_preview = _verified_placeholder_preview(case, request)
    manifest = _read(manifest_path)
    actual = {e['entity_id']: e for e in manifest['entities']}
    requested = {e['entity_id'] for e in request['entities']}
    if (len(actual) != len(manifest['entities']) or set(actual) != requested
            or set(geometry['entity_readbacks']) != requested):
        raise ValueError('Saved inventory differs from the frozen request/geometry')
    helpers = str(Path(__file__).resolve().parent /
                  'engine/source/scripts/internal/scene_generation/real_assets')
    if helpers not in sys.path:
        sys.path.insert(0, helpers)
    import furnishing_suitability
    from furnishing_suitability import audit_furnishing_geometry
    # Readback files contain measured extents, but not every collision mode
    # repeats identity fields. Bind those fields to the hash-checked ACTUAL
    # generated manifest; never take them from a requested/nominal candidate.
    bound_geometry = copy.deepcopy(geometry)
    for eid, readback in bound_geometry['entity_readbacks'].items():
        selected = actual[eid]
        collision = readback.get('collision_representation') or {}
        expected = {key: selected.get(key) for key in
                    ('asset_id', 'asset_sha256', 'runtime_sha256', 'canonical_transform')}
        expected.update(record_id=selected.get('pool_candidate_key'), source_sha256=selected.get('asset_sha256'))
        for scope in (collision, readback):
            for key, value in expected.items():
                if key in scope and scope[key] != value:
                    raise ValueError('Saved source identity mismatch: ' + eid + '/' + key)
        for key in ('asset_id', 'asset_sha256', 'runtime_sha256', 'canonical_transform', 'record_id'):
            readback.setdefault(key, copy.deepcopy(expected[key]))
    suitability = audit_furnishing_geometry(spec, request, bound_geometry)
    preferred = {r['entity_id']: r.get('preferred_candidate_record_ids', [])
                 for r in request['furniture']}
    choices = []
    for eid, entity in sorted(actual.items()):
        prefs = preferred[eid]
        record = entity.get('pool_candidate_key')
        choices.append(dict(entity_id=eid, asset_id=entity['asset_id'], record_id=record,
                            preferred_record_id=prefs[0] if prefs else None,
                            used_first_preference=record == prefs[0] if prefs else None,
                            fallback_reason='native_solver_qualification_or_joint_feasibility'
                                if prefs and record != prefs[0] else None))
    roles = {}
    for eid, entity in actual.items():
        role = entity.get('category') or entity.get('binding_semantic_key') or entity['role']
        roles.setdefault(role, []).append(entity['asset_id'])
    fulfillment_path=case / 'furnishing_fulfillment.json'
    coverage=None
    if fulfillment_path.is_file():
        import furnishing_fulfillment
        from furnishing_fulfillment import audit_saved_coverage, project_available_furnishing
        ledger=_read(fulfillment_path)
        original=_read(case / 'source_request.json')
        selection=_read(case / 'dynamic_selection.json')
        if selection.get('passed') is not True or selection.get('fulfillment')!=ledger:
            raise ValueError('Furnishing ledger differs from completed selection evidence')
        qualified=_read(case / 'qualified_goal_request.json')
        _,_,expected=project_available_furnishing(qualified,spec,original=original,
                                                 stop_reason=ledger.get('stop_reason'),
                                                 layout_omissions=ledger.get('layout_omissions'),
                                                 budget_evidence=ledger.get('budget_evidence'))
        if expected!=ledger:
            raise ValueError('Furnishing ledger differs from qualified goal inventory')
        coverage=audit_saved_coverage(original,request,actual,ledger)
        if not coverage['passed']:
            raise ValueError('Furnishing coverage evidence invalid: '+str(coverage['issues']))
    source_paths = [manifest_path, blend, geometry_path,
                    case / 'request.json', case / 'approved_scene_spec.json', output / 'result.json']
    if coverage is not None:
        source_paths.extend([fulfillment_path,case / 'source_request.json',
                             case / 'dynamic_selection.json',case / 'qualified_goal_request.json'])
    if placeholder_preview:
        source_paths.extend(placeholder_preview['paths'].values())
        source_paths.append(case / 'procedural_preview_receipt.json')
    evidence = dict(schema='rhg.furnishing-evaluation.v1',
        scope='saved_inventory_size_and_selection_review_not_robot_execution',
        native_geometry_complete=geometry.get('full_geometry_complete') is True,
        native_geometry_passed=geometry.get('full_geometry_passed') is True,
        native_visibility_passed=result.get('visibility_passed') is True,
        saved_entity_count=len(actual), distinct_asset_count=len({e['asset_id'] for e in actual.values()}),
        room_counts=dict(Counter(e['room_id'] for e in actual.values())),
        diversity_by_category={r: dict(instances=len(a), unique_sources=len(set(a))) for r, a in sorted(roles.items())},
        choices=choices, suitability=suitability, furnishing_coverage=coverage,
        procedural_placeholder_preview=(
            dict(preview_path=placeholder_preview['receipt']['preview_path'],
                 preview_sha256=placeholder_preview['receipt']['preview_sha256'],
                 layout_qualified=False) if placeholder_preview else None),
        deferred_requirements=_read(case / 'deferred_requirements.json'),
        complete_home_accepted=False, robot_execution='not_run',
        audit_code_sha256={str(p): _sha(p) for p in
            [Path(__file__).resolve(), Path(furnishing_suitability.__file__).resolve()]+
            ([Path(furnishing_fulfillment.__file__).resolve()] if coverage is not None else [])},
        sources={str(p): _sha(p) for p in source_paths})
    # Never edit native evidence to make proportions or discovery appear passed.
    with target.open('x', encoding='utf-8') as stream:
        json.dump(evidence, stream, ensure_ascii=False, indent=2, allow_nan=False)
        stream.write('\n')
    print(json.dumps(dict(furnishing_evaluation=str(target), entities=len(actual),
                          unique_assets=evidence['distinct_asset_count'],
                          robot_execution='not_run')), flush=True)
    return evidence