File size: 12,703 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
"""Conservative, evidence-bound bedside retry ordering; never source rejection."""
from __future__ import annotations
import copy
import hashlib
import json
import os
from pathlib import Path
import sqlite3
import sys
import time


def prioritize_sources(ranked, preferred):
    """Stable permutation only: cannot insert a source or bypass later gates."""
    if not isinstance(preferred, list) or not all(isinstance(a,str) for a in preferred):
        return ranked
    order={aid:i for i,aid in reversed(list(enumerate(preferred)))}
    return sorted(ranked,key=lambda row:order.get(row['asset_id'],len(order)))


def _sha(path):return hashlib.sha256(Path(path).read_bytes()).hexdigest()
def _read(path):return json.loads(Path(path).read_text())
def _fingerprint(value):return hashlib.sha256(json.dumps(value,sort_keys=True,separators=(',',':'),ensure_ascii=False).encode()).hexdigest()


def _target(original, selected, report, domains, excluded):
    if os.environ.get('RHG_LAYOUT_RECOVERY_POLICY')!='stable_group_v1':return None
    if report.get('passed') is not False or report.get('status')!='infeasible_on_declared_pose_grid':return None
    failed=[r for r in report.get('rooms',[]) if r.get('passed') is False]
    if len(failed)!=1 or failed[0].get('budget_exhausted'):return None
    entities={e['entity_id']:e for e in selected['entities']}
    from layout_recovery_evidence import structural_participants
    if structural_participants(report,entities) is not None:return None
    empty={r.get('entity_id') for r in failed[0].get('conflict_evidence',[])
           if r.get('reason')=='no_native_pose_domain' and type(r.get('count')) is int and r['count']>0}
    original_rules={r['entity_id']:r for r in original['furniture']}
    selected_rules={r['entity_id']:r for r in selected['furniture']}
    fixed={e['entity_id'] for source in (original,selected) for e in source.get('search_constraints',{}).get('fixed_entities',[])}
    pairs=[]
    for child_id in sorted(empty):
        child=entities.get(child_id,{})
        parent_id=child.get('front_target_entity_id');parent=entities.get(parent_id,{})
        if (child.get('role')!='side_table' or child.get('category')!='nightstand' or parent.get('role')!='bed'
                or parent.get('room_id')!=failed[0]['room_id'] or child.get('room_id')!=parent.get('room_id')
                or child.get('layout_relation')!='nightstand_back_flush_with_bed_head_wall'
                or child.get('requirements',{}).get('best_effort_furnishing') is not True
                or child.get('requirements',{}).get('automatic_front_target_entity_id')!=parent_id
                or parent_id in fixed or child_id in fixed):continue
        pin=original_rules[parent_id]
        if any(pin.get(k) for k in ('asset_id','record_id','source_sha256','asset_sha256','runtime_sha256','canonical_transform')):continue
        current=set(selected_rules[parent_id].get('candidate_asset_ids',[]))
        if len(current)!=1 or len(selected_rules[child_id].get('candidate_asset_ids',[]))!=1:continue
        allowed=[a for a in domains.get(parent_id,[]) if a not in current and a not in excluded.get(parent_id,[])]
        if pin.get('candidate_asset_ids'):allowed=[a for a in allowed if a in pin['candidate_asset_ids']]
        if allowed:pairs.append((parent_id,child_id,allowed))
    return pairs[0] if len(pairs)==1 else None


def _context(previous_case, feedback, selected):
    path=Path(feedback['path']).resolve();attempt=Path(feedback['attempt']).resolve()
    if previous_case not in path.parents or attempt!=path.parents[2]:raise ValueError('feedback_path')
    if _sha(path)!=feedback['sha256'] or _read(path)!=feedback['report']:raise ValueError('stale_feedback')
    report=feedback['report'];request_path=attempt/'request.json'
    if _sha(request_path)!=report['request_sha256']:raise ValueError('request_binding')
    request=_read(request_path)
    for key in ('entities','furniture','floor_plan_sha256'):
        if request.get(key)!=selected.get(key):raise ValueError('selected_native_binding')
    generated=path.parent;manifest_path=generated.parent/'_requested_shell'/generated.name/'composition_manifest.runtime.json'
    replay_path=generated/'selection_replay.json';manifest=_read(manifest_path)
    if _sha(manifest_path)!=_read(replay_path)['inputs']['source_manifest_sha256']:raise ValueError('manifest_binding')
    shell_path=generated/'shell_geometry_input.json'
    if (_sha(shell_path)!=report['structural_constraint_evidence']['shell_input_sha256']
            or Path(report['structural_constraint_evidence']['shell_input_path']).resolve()!=shell_path):raise ValueError('shell_binding')
    request.update(copy.deepcopy(report['effective_policies']))
    runtime_path=attempt/'runtime.json'
    paths=[path,request_path,manifest_path,shell_path,replay_path,runtime_path]
    evidence={str(p):_sha(p) for p in paths}
    return manifest,request,_read(shell_path),_read(runtime_path),evidence


def _catalog(runtime, wanted):
    """Read sealed measured records. These are not current-entity admissions."""
    catalog={};evidence={};parent=None
    for key in ('prepared_asset_pool','supplemental_prepared_pool'):
        if not runtime.get(key):continue
        path=Path(runtime[key]);receipt_path=path.with_suffix('.receipt.json');receipt=_read(receipt_path);digest=_sha(path)
        if (receipt.get('schema')!='rhg.prepared_asset_pool.v2' or digest!=receipt.get('sha256')
                or parent is not None and receipt.get('parent_pool_sha256')!=parent):raise ValueError('prepared_pool_binding')
        parent=parent or digest;evidence[str(path)]=digest;evidence[str(receipt_path)]=_sha(receipt_path)
        with sqlite3.connect(path.resolve().as_uri()+'?mode=ro',uri=True) as db:
            for rid,aid,raw,geo_raw,sup_raw in db.execute('SELECT candidate_key,asset_id,candidate_json,geometry_json,support_json FROM candidates'):
                if aid not in wanted:continue
                c=json.loads(raw);geo=json.loads(geo_raw);sup=json.loads(sup_raw)
                if (c.get('asset_id')!=aid or c.get('pool_candidate_key')!=rid or not geo.get('passed') or not sup.get('passed')
                        or geo.get('dimensions_m')!=c.get('dimensions_m')):continue
                c['source_support_geometry']=sup.get('source_support_geometry')
                catalog.setdefault(aid,[]).append(c)
    return catalog,evidence


def _resolved(candidate,reader,request,entity,evidence):
    candidate=copy.deepcopy(candidate)
    for path_key,hash_key in (('canonical_path','asset_sha256'),('runtime_path','runtime_sha256')):
        path=Path(candidate[path_key]);expected=candidate[hash_key]
        if str(path) in evidence:
            if evidence[str(path)]!=expected:raise ValueError('source_hash_conflict')
        else:
            if _sha(path)!=expected:raise ValueError('source_bytes_changed')
            evidence[str(path)]=expected
    attributes,reason=reader.consume(candidate,request,entity,verify_files=True)
    if reason:return None
    resolution=(attributes or {}).get('functional_front_resolution') or {}
    if resolution.get('effective_axis'):
        candidate['functional_front_resolution']=resolution
        candidate['canonical_front_axis']=resolution['effective_axis']
        candidate['prior_prepared_source_frame_contract']=copy.deepcopy(candidate.get('prepared_source_frame_contract'))
        candidate['prepared_source_frame_contract']['canonical_front_axis']=resolution['effective_axis']
    return candidate


def recommend_bedside_sources(root_case, previous_case, feedback, original, selected,
                              domains, excluded, runtime, engine, *, max_candidates=16,
                              max_parent_poses=256, timeout_s=40):
    """Return a reversible ordering hint only with an empty current pair and a witness.

    Unknown source, changed evidence, ambiguous pins, geometry/budget uncertainty
    all preserve the old selection. Time limits are cooperative at native calls.
    """
    started=time.monotonic()
    def remaining():return timeout_s-(time.monotonic()-started)
    try:
        target=_target(original,selected,feedback['report'],domains,excluded)
        if target is None:return None
        if type(max_candidates) is not int or max_candidates<1 or type(max_parent_poses) is not int or max_parent_poses<1 or timeout_s<=0:return None
        parent_id,child_id,allowed=target
        previous_case=Path(previous_case).resolve();root_case=Path(root_case).resolve()
        if previous_case!=root_case and root_case not in previous_case.parents:return None
        engine=Path(engine);sys.path[:0]=[str(engine),str(engine/'source'),str(engine/'source/scripts/internal/scene_generation/real_assets')]
        from real_test.run_three_houses import case_environment,environment_scope
        with environment_scope(case_environment(previous_case,native=True)):
            manifest,request,shell,native_runtime,evidence=_context(previous_case,feedback,selected)
            rules={r['entity_id']:r for r in selected['furniture']};entities={e['entity_id']:e for e in selected['entities']}
            current={eid:rules[eid]['candidate_asset_ids'][0] for eid in (parent_id,child_id)}
            catalog,inputs=_catalog(native_runtime,set(allowed)|set(current.values()));evidence.update(inputs)
            def selected_record(eid):
                rows=[c for c in catalog.get(current[eid],[]) if c['pool_candidate_key'] in rules[eid].get('candidate_record_ids',[])]
                return rows[0] if len(rows)==1 else None
            parent,child=selected_record(parent_id),selected_record(child_id)
            if parent is None or child is None or remaining()<=0:return None
            release=Path(native_runtime['attribute_release']);evidence[str(release)]=_sha(release)
            from style_attribute_consumer import load_attribute_releases
            reader=load_attribute_releases(str(release))
            attribute_request=dict(request,relations=feedback['report']['relations'])
            parent=_resolved(parent,reader,attribute_request,entities[parent_id],evidence)
            child=_resolved(child,reader,attribute_request,entities[child_id],evidence)
            if parent is None or child is None or remaining()<=0:return None
            from bedside_probe import probe_bedside_pair
            def probe(candidate):
                return probe_bedside_pair(manifest,request,shell,candidate,child,parent_id,child_id,
                    envelope_report=feedback['report'].get('envelope_layout'),max_parent_poses=max_parent_poses,
                    timeout_s=min(8,max(.001,remaining())))
            failed=probe(parent)
            if failed['status']!='empty' or remaining()<=0:return None
            pin=next(r for r in original['furniture'] if r['entity_id']==parent_id)
            refs=set(pin.get('candidate_record_ids',[]));checked=[];preferred=[]
            for aid in allowed:
                rows=[c for c in catalog.get(aid,[]) if not refs or c['pool_candidate_key'] in refs]
                if len(rows)!=1:continue
                if len(checked)>=max_candidates or remaining()<=0:break
                candidate=_resolved(rows[0],reader,attribute_request,entities[parent_id],evidence)
                if candidate is None:
                    checked.append(dict(asset_id=aid,status='unknown',reason='attribute_qualification_unavailable'));continue
                result=probe(candidate);checked.append(dict(asset_id=aid,record_id=candidate['pool_candidate_key'],probe=result))
                if result['status']=='witness':
                    preferred.append(aid)
                    # One verified witness is enough; all other sources stay in original order.
                    break
            if not preferred or remaining()<=0:return None
            if any(_sha(p)!=h for p,h in evidence.items()):return None
            return dict(parent_entity_id=parent_id,child_entity_id=child_id,preferred_asset_ids=preferred,
                evidence=dict(schema='rhg.bedside-recovery-order.v1',inputs_sha256=evidence,
                    original_request_sha256=_fingerprint(original),selected_request_sha256=_fingerprint(selected),
                    failed_pair=failed,candidates_checked=checked,elapsed_s=round(time.monotonic()-started,6),
                    selection_effect='stable_permutation_only_full_qualification_required',
                    max_candidates=max_candidates,max_parent_poses=max_parent_poses,timeout_s=timeout_s))
    except Exception:
        # Advisory ordering must never turn a cold/incomplete diagnostic into a new failure.
        return None