Datasets:
File size: 17,911 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 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 | """Ordered saved-scene validation; navigation evidence is not task delivery."""
from __future__ import annotations
import argparse
import hashlib
import gzip
import json
import math
import os
from pathlib import Path
import signal
import subprocess
import sys
import time
def sha(path):
digest = hashlib.sha256()
with Path(path).open('rb') as stream:
for block in iter(lambda: stream.read(1024 * 1024), b''):
digest.update(block)
return digest.hexdigest()
def read_json(path):
return json.loads(Path(path).read_text())
def write_json(path, value):
Path(path).write_text(json.dumps(value, indent=2, allow_nan=False) + '\n')
def source_inputs(scene, task):
runtime_path = scene / 'composition_manifest.runtime.json'
runtime = read_json(runtime_path)
identifier = runtime['scene_id']
if not isinstance(identifier, str) or Path(identifier).name != identifier or identifier in {'.', '..'}:
raise ValueError('Invalid saved scene identifier')
blend = scene / (identifier + '.blend')
entities = runtime['entities']
ids = [e['entity_id'] for e in entities]
if not ids or len(set(ids)) != len(ids):
raise ValueError('Missing or duplicate saved entities')
value = read_json(task)
route = value['route_waypoints_xy_m']
if len(route) < 2 or any(len(p) != 2 or any(
isinstance(x, bool) or not isinstance(x, (int, float)) or not math.isfinite(x) for x in p) for p in route):
raise ValueError('Invalid task route')
start = value['robot_start_pose']
if math.dist([start['x_m'], start['y_m']], route[0]) > .02:
raise ValueError('Task route does not start at robot start pose')
for endpoint in ('pick', 'place'):
item = value[endpoint]
pose = item['approach_pose']
numbers = list(item['position_xyz_m']) + [pose[k] for k in ('x_m', 'y_m', 'yaw_deg')]
if len(numbers) != 6 or any(isinstance(x, bool) or not isinstance(x, (int, float))
or not math.isfinite(x) for x in numbers):
raise ValueError('Invalid task endpoint')
if not any(math.dist([pose['x_m'], pose['y_m']], p) < 1e-5 for p in route):
raise ValueError('Task approach is absent from route')
if math.dist([pose['x_m'], pose['y_m']], route[-1]) >= 1e-5:
raise ValueError('Task route does not end at place approach')
paths = [runtime_path, blend, task]
provenance = value.get('generation_task_provenance')
plan_path = scene/'generation_task_plan.json'
if provenance is not None or (task.name == 'trial_task.json' and plan_path.exists()):
if not isinstance(provenance, dict) or provenance.get('schema') != 'rhg.generated-task-source.v1':
raise ValueError('Generated task source marker is missing or invalid')
required = ('composition_manifest.runtime.json', 'SceneManifest.v16.json',
'BenchmarkEpisode.v16.json', 'task_entity_contract.json',
'task_binding_sync_report.json', blend.name)
generated_sources = [scene/name for name in required]
composition_path = scene/'trial_composition.json'
generated_paths = [*generated_sources, plan_path, composition_path]
if any(not path.is_file() or path.is_symlink() for path in generated_paths):
raise ValueError('Generated task evidence is missing or not a regular file')
source_hashes = {path.name: sha(path) for path in generated_sources}
plan = read_json(plan_path)
outputs = {'trial_task.json': sha(task), 'trial_composition.json': sha(composition_path)}
if (plan.get('schema') != 'rhg.generation-task-plan.v1' or plan.get('passed') is not True
or plan.get('whole_task_acceptance') is not False
or provenance.get('source_files_sha256') != source_hashes
or plan.get('source_files_sha256') != source_hashes
or plan.get('output_sha256') != outputs):
raise ValueError('Generated task plan is failed, stale or inconsistent with the saved scene')
paths = list(dict.fromkeys([*paths, *generated_paths]))
if any(not p.is_file() or p.is_symlink() for p in paths):
raise ValueError('Source inputs must be regular files')
return {'source_blend_sha256': sha(blend), 'task_sha256': sha(task),
'runtime_sha256': sha(runtime_path), 'blend': str(blend),
'runtime': str(runtime_path), 'task': str(task),
'input_sha256': {str(p): sha(p) for p in paths}}
def validate_geometry(root, inputs):
from .geometry.prepare import physical_floor_support, audit_route_floor, audit_floor_sweep
from .geometry.rug_route import analyze_rugs
from .native.rug_contract import validate_rug_contract
report = read_json(root / 'geometry_report.json')
expected = {key: inputs[key] for key in ('source_blend_sha256', 'task_sha256', 'runtime_sha256')}
expected.update(source_meshes_sha256=sha(root / 'physical_meshes.json.gz'),
collision_usd_sha256=sha(root / 'collision_usd/house.usdc'))
if (report.get('schema') != 'rhg.sim2real-geometry.v1' or report.get('passed') is not True
or report.get('all_source_inputs_unchanged') is not True
or any(report.get(k) != v for k, v in expected.items())):
raise ValueError('Geometry evidence source binding failed')
artifacts = ('floor_support_validation.json', 'floor_sweep_validation.json',
'collision_usd/manifest.json', 'rug_route_contract.json')
if report.get('evidence_sha256') != {name: sha(root / name) for name in artifacts}:
raise ValueError('Geometry stage artifact binding failed')
task, runtime = read_json(inputs['task']), read_json(inputs['runtime'])
with gzip.open(root / 'physical_meshes.json.gz', 'rt') as stream:
payload = json.load(stream)
# The exporter carries the runtime fields needed by collision consumers.
entity_fields = ('entity_id', 'asset_id', 'asset_sha256', 'runtime_sha256', 'category',
'dimensions_m', 'actual_center_xy_m', 'center_xy_m', 'base_z_m')
exported_entities = [{key: entity.get(key) for key in entity_fields}
for entity in runtime['entities']]
if (payload.get('source_runtime_sha256') != inputs['runtime_sha256']
or payload.get('source_blend_sha256') != inputs['source_blend_sha256']
or payload.get('geometry_modified') is not False or payload.get('blend_saved') is not False
or payload.get('entities') != exported_entities):
raise ValueError('Mesh payload source binding failed')
manifest = read_json(root / 'collision_usd/manifest.json')
manifest_bindings = dict(source_blend_sha256=expected['source_blend_sha256'],
source_meshes_sha256=expected['source_meshes_sha256'],
usd_sha256=expected['collision_usd_sha256'])
if (manifest.get('schema') != 'rhg.saved-house-collision-usd.v1'
or manifest.get('usd') != 'house.usdc'
or any(manifest.get(k) != v for k, v in manifest_bindings.items())
or manifest.get('entities') != payload['entities']
or manifest.get('mesh_count') != len(payload['meshes'])
or manifest.get('triangle_count') != sum(len(m['triangles']) for m in payload['meshes'])
or payload.get('mesh_count') != manifest.get('mesh_count')
or payload.get('triangle_count') != manifest.get('triangle_count')):
raise ValueError('Collision manifest source binding failed')
mesh_rows, mapping = [], {}
for index, mesh in enumerate(payload['meshes']):
identifier = mesh['entity_id'] or '__shell__'
group = hashlib.sha256(identifier.encode()).hexdigest()[:16]
prim = f'/House/E_{group}/Mesh_{index:04d}'
mapping.setdefault(identifier, []).append(prim)
mesh_rows.append(dict(name=mesh['name'], entity_id=mesh['entity_id'], prim_path=prim,
vertices=len(mesh['vertices']), triangles=len(mesh['triangles'])))
if manifest.get('meshes') != mesh_rows or manifest.get('entity_prim_paths') != mapping:
raise ValueError('Collision manifest mesh inventory binding failed')
stage_bindings = {k: v for k, v in expected.items() if k != 'collision_usd_sha256'}
support, floor_rows = physical_floor_support(payload)
center = audit_route_floor(task['route_waypoints_xy_m'], support)
sweep = audit_floor_sweep(task['route_waypoints_xy_m'], support)
for filename, schema in [('floor_support_validation.json', 'rhg.actual-floor-support-audit.v1'),
('floor_sweep_validation.json', 'rhg.actual-floor-full-radius-sweep.v1')]:
evidence = read_json(root / filename)
if (evidence.get('schema') != schema or evidence.get('passed') is not True
or any(evidence.get(k) != v for k, v in stage_bindings.items())):
raise ValueError('Floor evidence source binding failed')
if filename == 'floor_support_validation.json':
if (not center['continuous_centerline_supported']
or evidence.get('dense_and_continuous_route_audit') != center
or evidence.get('actual_floor_meshes') != floor_rows):
raise ValueError('Floor support differs from actual mesh geometry')
elif not sweep['passed'] or any(evidence.get(k) != v for k, v in sweep.items()):
raise ValueError('Floor sweep differs from actual mesh geometry')
contract = read_json(root / 'rug_route_contract.json')
validate_rug_contract(contract, task, manifest, inputs['task_sha256'])
if any(contract.get(k) != v for k, v in expected.items()):
raise ValueError('Rug contract source binding failed')
derived = json.loads(json.dumps(analyze_rugs(payload, task)))
if any(contract.get(k) != v for k, v in derived.items()):
raise ValueError('Rug contract differs from actual mesh geometry')
return report
def execute(command, *, log, env, timeout):
"""Bound only our new process group, including a simulator's children."""
with log.open('x') as stream:
stream.write(json.dumps(command) + '\n')
stream.flush()
with subprocess.Popen(command, cwd=Path(__file__).resolve().parents[2], env=env,
stdout=stream, stderr=subprocess.STDOUT, start_new_session=True) as child:
try:
return child.wait(timeout=timeout)
except subprocess.TimeoutExpired:
os.killpg(child.pid, signal.SIGTERM)
try:
child.wait(timeout=15)
except subprocess.TimeoutExpired:
os.killpg(child.pid, signal.SIGKILL)
child.wait()
return 124
def parse_args(argv=None):
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('--scene', required=True, type=Path)
parser.add_argument('--task', required=True, type=Path)
parser.add_argument('--out', required=True, type=Path)
parser.add_argument('--blender')
parser.add_argument('--runtime-config', type=Path)
parser.add_argument('--geometry-input', type=Path,
help='Previously prepared geometry with exact matching input hashes, for host handoff.')
parser.add_argument('--stop-after', choices=('geometry', 'navigation'), default='navigation')
parser.add_argument('--timeout', type=int, default=600)
parser.add_argument('--duration', type=float, default=180.)
return parser.parse_args(argv)
def run(args):
scene, task, out = args.scene.resolve(), args.task.resolve(), args.out.resolve()
if out.is_relative_to(scene) or task.is_relative_to(out) or scene.is_relative_to(out):
raise ValueError('Output must be outside the source scene and task')
if args.timeout <= 0 or not math.isfinite(args.duration) or args.duration <= 0:
raise ValueError('Timeout and duration must be positive')
if not args.geometry_input and not args.blender:
raise ValueError('Fresh geometry requires --blender')
if args.stop_after == 'navigation' and not args.runtime_config:
raise ValueError('Native validation requires --runtime-config')
inputs = source_inputs(scene, task)
out.mkdir(parents=True, exist_ok=False)
logs = out / 'logs'
logs.mkdir()
root = Path(__file__).resolve().parents[2]
env = os.environ.copy()
env['PYTHONDONTWRITEBYTECODE'] = '1'
env['PYTHONPATH'] = str(root) + os.pathsep + env.get('PYTHONPATH', '')
report = {'schema': 'rhg.sim2real.staged-validation.v1', 'source_inputs': inputs,
'requested_stop_after': args.stop_after, 'commands': [],
'requested_scope_passed': False, 'whole_task_acceptance': False,
'gates': {'geometry': 'not_run', 'native_position_ik': 'not_run',
'native_navigation': 'not_run', 'physical_manipulation': 'not_run',
'material_simready': 'not_run', 'rparena_task_acceptance': 'not_run'}}
report_path = out / 'sim2real_report.json'
def record(name, command, *, command_env=None):
started = time.monotonic()
log = logs / (name + '.log')
code = execute(command, log=log, env=command_env or env, timeout=args.timeout)
report['commands'].append({'stage': name, 'command': command, 'exit_code': code,
'elapsed_s': time.monotonic() - started, 'log': str(log),
'timeout_reason': 'subprocess_stage_timeout' if code == 124 else None})
write_json(report_path, report)
if code:
raise ValueError(f'{name} failed with exit code {code}')
try:
geometry = args.geometry_input.resolve() if args.geometry_input else out / 'geometry'
if not args.geometry_input:
geometry.mkdir()
record('01_export_collision_meshes', [args.blender, '-b', '--python-use-system-env',
'--threads', '4', '--python-exit-code', '1', '--python',
str(root / 'packages/sim2real/geometry/export_meshes.py'), '--', '--scene', str(scene),
'--out', str(geometry / 'physical_meshes.json.gz')])
record('02_prepare_geometry', [sys.executable, '-m', 'packages.sim2real.geometry.prepare',
'--scene', str(scene), '--task', str(task), '--out', str(geometry)])
report['geometry'] = validate_geometry(geometry, inputs)
report['geometry_root'] = str(geometry)
report['geometry_evidence_sha256'] = sha(geometry / 'geometry_report.json')
report['rug_contract_sha256'] = sha(geometry / 'rug_route_contract.json')
report['gates']['geometry'] = 'passed'
if args.stop_after == 'navigation':
config = read_json(args.runtime_config)
native_env = env.copy()
native_env['CUDA_VISIBLE_DEVICES'] = ''
native_env['PYTHONPATH'] = os.pathsep.join([str(root), *config.get('pythonpath', []),
env.get('PYTHONPATH', '')])
common = [config['python'], '-m']
record('03_native_position_ik', common + ['packages.sim2real.reach.solve',
'--sdk-root', config['sdk_root'], '--urdf', str(Path(config['assets']) /
'wbc_robot_model/g1_29dof_with_hand.urdf'), '--task', str(task),
'--out', str(out / 'native_position_ik.json')], command_env=native_env)
reach = read_json(out / 'native_position_ik.json')
if reach.get('passed') is not True or reach.get('task_sha256') != inputs['task_sha256']:
raise ValueError('Native position IK evidence failed or mismatched task')
report['gates']['native_position_ik'] = 'passed_position_only'
dependency_args = [arg for path in config.get('pythonpath', []) for arg in ('--pythonpath', path)]
record('04_native_navigation', common + ['packages.sim2real.native.checked_runner',
'--python', config['python'], '--sdk-root', config['sdk_root'], '--assets', config['assets'],
'--out', str(out / 'native_navigation'), '--task', str(task),
'--collision-dir', str(geometry / 'collision_usd'),
'--source-blend-sha256', inputs['source_blend_sha256'],
'--rug-contact-contract', str(geometry / 'rug_route_contract.json'),
'--timeout', str(max(1, args.timeout - 20)), '--duration', str(args.duration), *dependency_args],
command_env=native_env)
from .native.verify_attempt import verify
verified = verify(out / 'native_navigation', task,
expected_contract_sha=report['rug_contract_sha256'])
if verified.get('passed') is not True:
raise ValueError('Native raw evidence independent verification failed')
report['native_verification'] = verified
report['gates']['native_navigation'] = 'passed'
if any(sha(Path(p)) != digest for p, digest in inputs['input_sha256'].items()):
raise ValueError('Source input changed during validation')
report.update(status='geometry_ready' if args.stop_after == 'geometry' else 'navigation_validated',
requested_scope_passed=True, all_source_inputs_unchanged=True)
write_json(report_path, report)
return 0
except Exception as error:
report.update(status='failed', error=f'{type(error).__name__}: {error}')
write_json(report_path, report)
return 1
def main(argv=None):
return run(parse_args(argv))
if __name__ == '__main__':
raise SystemExit(main())
|