RoboHome / code /robohome /src /engine /real_test /replay_joint_layout.py
RoboParty Release
Unify robohome source, assets and scenes delivery
3f15e9f
Raw History Blame Contribute Delete
10.7 kB
"""Replay native search from retained binding inputs; never qualify a scene."""
from __future__ import annotations
import argparse
from collections import Counter
import hashlib
import json
import os
from pathlib import Path
import sys
import time
import traceback
ROOT = Path(__file__).resolve().parents[1]
def digest(path):
return hashlib.sha256(Path(path).read_bytes()).hexdigest()
def load(path):
return json.loads(Path(path).read_text())
def save(path, value):
Path(path).write_text(json.dumps(value, indent=2, ensure_ascii=False,
allow_nan=False) + '\n')
def prepare_output(case, output):
case, output = Path(case).resolve(), Path(output).resolve()
if case == output or case in output.parents or output in case.parents:
raise ValueError('Replay output must not overlap the retained case')
output.mkdir(parents=True, exist_ok=False)
return output
def replay(case, output, *, code_root=ROOT, expected_entities=55):
case, code_root = Path(case).resolve(), Path(code_root).resolve()
if ROOT / 'runs' not in Path(output).resolve().parents:
raise ValueError('Replay output must be a new directory under this version/runs')
output = prepare_output(case, output)
started = time.monotonic()
result = dict(schema='rhg.native-search-replay.v1', passed=False,
case=str(case), code_root=str(code_root),
fresh_house_generated=False, scene_assembled=False,
physical_qualified=False, whole_task_acceptance=False,
constraints_modified=False, budget_modified=False)
inputs, before = {}, {}
try:
attempt = case / 'execution/chain/round_01/attempt_01'
stage_log = attempt / 'native_stage_00.log'
stages = []
for line in stage_log.read_text().splitlines():
try:
stages.append(json.loads(line))
except json.JSONDecodeError:
continue
bind = next(row for row in stages if row.get('event') == 'stage_done'
and row.get('name') == 'bind_prepared_0')
argv = bind['argv']
scene = Path(argv[argv.index('--output-scene') + 1])
source = Path(argv[argv.index('--source-scene') + 1])
paths = dict(manifest=source / 'composition_manifest.runtime.json',
snapshot=scene / '_candidate_snapshot.json',
request=scene / 'eligible_scene_request.json',
shell=scene / 'shell_geometry_input.json',
runtime=attempt / 'runtime.json',
replay=scene / 'selection_replay.json',
prior_report=scene / 'joint_search_report.json')
if any(case not in path.resolve().parents for path in paths.values()):
raise ValueError('Retained bind inputs escape the selected case')
inputs = {str(path): digest(path) for path in paths.values()}
inputs[str(stage_log)] = digest(stage_log)
runtime, prior = load(paths['runtime']), load(paths['prior_report'])
manifest, candidates = load(paths['manifest']), load(paths['snapshot'])
selection = load(paths['replay'])
if digest(paths['manifest']) != selection['inputs']['source_manifest_sha256']:
raise ValueError('Manifest differs from the retained binding receipt')
if digest(paths['request']) != prior['request_sha256']:
raise ValueError('Eligible request differs from the retained search report')
shell_sha = prior['structural_constraint_evidence']['shell_input_sha256']
if digest(paths['shell']) != shell_sha:
raise ValueError('Shell differs from retained native readback evidence')
if len(manifest['entities']) != expected_entities:
raise ValueError('Replay must retain all expected entities')
result['entity_count'] = len(manifest['entities'])
result['candidate_count'] = len(candidates)
code = code_root / 'source/scripts/internal/scene_generation/real_assets'
helpers = code.parent
before = {str(p): digest(p) for p in code.glob('*.py')}
before[str(Path(__file__).resolve())] = digest(__file__)
save(output / 'provenance_before.json', dict(input_sha256=inputs,
implementation_sha256=before, original_bind=bind))
# Use only this revision's native modules and its private dependency site.
sys.path[:0] = [str(code), str(helpers), str(code_root / 'source'),
str(code_root / 'inputs/native_site')]
for key in list(os.environ):
if key.startswith('RHG_'):
os.environ.pop(key)
os.environ['RHG_WINDOW_GEOMETRY'] = str(paths['shell'])
for key, env in [('prepared_support_surfaces', 'RHG_PREPARED_SUPPORT_SURFACES'),
('prepared_floor_body_geometry', 'RHG_PREPARED_FLOOR_BODY_GEOMETRY')]:
if runtime.get(key):
os.environ[env] = runtime[key]
inputs[runtime[key]] = digest(runtime[key])
import joint_layout
import support_regions
from style_attribute_consumer import load_attribute_releases
if Path(joint_layout.__file__).resolve() != code / 'joint_layout.py':
raise ValueError('Replay imported another revision of native search')
request = joint_layout.load_request(paths['request'])
if len(request['furniture']) != expected_entities:
raise ValueError('Effective request lost entities')
if request['search'] != prior['effective_policies']['search']:
raise ValueError('Replay search policy differs from the failed run')
for ref in request.get('support_surface_feedback', []):
inputs[ref['path']] = digest(ref['path'])
if inputs[ref['path']] != ref['sha256']:
raise ValueError('Retained support feedback changed')
attribute_path = runtime['attribute_release']
inputs[attribute_path] = digest(attribute_path)
print('Loading original attribute reader', flush=True)
reader = load_attribute_releases(attribute_path)
contacts, samples, domains = Counter(), {}, []
original_contact = support_regions.contact_pose
original_positions = joint_layout.positions
def contact(parent, child):
value, errors = original_contact(parent, child)
if child.get('room_id') == 'kitchen':
reasons = [e.get('reason', 'unknown') for e in errors] or ['passed']
for reason in reasons:
key = (child['entity_id'], child.get('asset_id'), reason)
contacts[key] += 1
if key not in samples:
samples[key] = dict(entity_id=key[0], asset_id=key[1],
reason=reason, errors=errors, center_xy_m=child.get('center_xy_m'),
yaw_deg=child.get('yaw_deg'), base_z_m=child.get('base_z_m'),
parent_asset_id=parent.get('asset_id'),
parent_center_xy_m=parent.get('center_xy_m'),
parent_yaw_deg=parent.get('yaw_deg'))
return value, errors
def positions(entity, candidate, room, plan, assigned, req, constraints=None):
poses = original_positions(entity, candidate, room, plan, assigned, req,
constraints=constraints)
if entity.get('layout_slot_id') == 'kitchen_cooktop':
domains.append(dict(asset_id=candidate['asset_id'], pose_count=len(poses),
parent_pose={k: assigned.get(entity.get('supported_by_entity_id'), {}).get(k)
for k in ('asset_id', 'center_xy_m', 'yaw_deg', 'base_z_m')}))
return poses
support_regions.contact_pose = contact
joint_layout.positions = positions
print('Solving all retained entities with unchanged budgets', flush=True)
try:
choices, report = joint_layout.solve(manifest, candidates, request, output,
reader, committed_counts=selection['initial_committed_counts'])
save(output / 'selected_poses.json', {eid: {k: row[1].get(k) for k in
('asset_id', 'center_xy_m', 'yaw_deg', 'base_z_m', 'dimensions_m',
'support_contact_measurement')} for eid, row in choices.items()})
result['solver_passed'] = report['passed']
finally:
support_regions.contact_pose = original_contact
joint_layout.positions = original_positions
save(output / 'contact_diagnostics.json', dict(
samples=[dict(samples[k], count=n) for k, n in contacts.items()],
cooktop_domains=domains, observations_only=True))
result.update(solver_status=report['status'], passed=bool(result['solver_passed']))
except Exception as error:
result['failure'] = dict(type=type(error).__name__, message=str(error))
(output / 'traceback.log').write_text(traceback.format_exc())
finally:
report_path = output / 'joint_search_report.json'
if report_path.is_file():
native_report = load(report_path)
result['solver_status'] = native_report['status']
result['solver_passed'] = native_report['passed']
result['input_sha256'] = inputs
result['implementation_sha256'] = before
result['inputs_unchanged'] = all(Path(p).is_file() and digest(p) == sha
for p, sha in inputs.items())
result['implementation_unchanged'] = all(Path(p).is_file() and digest(p) == sha
for p, sha in before.items())
result['passed'] &= result['inputs_unchanged'] and result['implementation_unchanged']
result['elapsed_s'] = round(time.monotonic() - started, 3)
save(output / 'result.json', result)
print(json.dumps({k: v for k, v in result.items()
if k not in ('input_sha256', 'implementation_sha256')}), flush=True)
return result
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('--case', required=True, type=Path)
parser.add_argument('--output', required=True, type=Path)
parser.add_argument('--code-root', type=Path, default=ROOT)
args = parser.parse_args()
return 0 if replay(args.case, args.output, code_root=args.code_root)['passed'] else 1
if __name__ == '__main__':
raise SystemExit(main())