File size: 9,811 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
"""One explicit real-house smoke run, without seed retries or robot claims."""
import argparse
import importlib.util
import json
import os
from pathlib import Path
import shutil
import sys
import time


VERSION = Path(__file__).resolve().parents[1]
SOURCE = VERSION / 'source'
EVAL = Path(os.environ.get('RHG_EVAL_ROOT', VERSION / 'runs'))
TEMPLATE = Path(os.environ.get('RHG_REAL_HOUSE_TEMPLATE', EVAL / 'real_house_template'))
ROLE_HELPER = Path(os.environ.get('RHG_ROLE_HELPER', EVAL / 'run_one_regression.py'))
PROJECT_HELPER = Path(os.environ.get('RHG_PROJECT_HELPER', EVAL / 'generation_request.py'))
sys.path[:0] = [str(VERSION), str(SOURCE),
               str(SOURCE / 'scripts/internal/scene_generation/real_assets')]
from run_chain import base_identity, digest, load, run_chain, save
from process_control import execute_command
from real_test.projection_adapter import project_with_semantic_preservation


def module(name, path):
    spec = importlib.util.spec_from_file_location(name, path)
    value = importlib.util.module_from_spec(spec)
    spec.loader.exec_module(value)
    return value


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument('--output', type=Path, required=True)
    parser.add_argument('--generation-python', type=Path, default=Path(sys.executable))
    args = parser.parse_args()
    root = args.output.resolve()
    if VERSION not in root.parents:
        raise ValueError('Use a new output directory inside this isolated version')
    root.mkdir(parents=True, exist_ok=False)
    started = time.monotonic()
    result = dict(schema='rhg.frontier-real-house-smoke.v1', passed=False,
                  physical_qualified=False, whole_task_acceptance=False,
                  automatic_retry=False, gpu_used=False, stages=[])
    inputs = {str(path): digest(path) for path in (
        Path(__file__), TEMPLATE / 'runtime.json', TEMPLATE / 'request.json',
        ROLE_HELPER, PROJECT_HELPER,
        EVAL / 'inputs/attempt4/house05/composition_manifest.runtime.json')}

    def stage(name, argv, timeout):
        receipt = execute_command(argv, SOURCE, root / (name + '.log'), timeout)
        result['stages'].append(dict(name=name, **receipt))
        save(root / 'stages.json', result['stages'])
        if receipt['exit_code'] or receipt['timed_out'] or not receipt['cleanup_passed']:
            raise RuntimeError(name + ' failed; original log and receipt retained')

    try:
        identity = base_identity()
        if not identity['passed']:
            raise ValueError('Saved baseline identity failed before real execution')
        result['base_identity_before'] = identity
        config = load(TEMPLATE / 'runtime.json')
        seed = config['seed']
        generation_python = str(args.generation_python.absolute())
        config.update(asset_bundle=None, python=generation_python,
            blender=os.environ.get('RHG_BLENDER', 'blender'),
            out_root=str(root / 'generated'), jobs_root=str(root / 'jobs'),
            cache_root=str(root / 'cache'), usage_ledger=str(root / 'usage.json'),
            baseline_root=str(root / 'fresh_layout'), joint_request=None,
            mdl_bake_cache=str(root / 'mdl-cache'), cuda_kernel_cache_root=str(root / 'cuda-cache'),
            rplan_seeds=os.environ.get(
                'RHG_RPLAN_SEEDS', str(SOURCE / 'configs/floorplans/rplan_production_16.json')),
            scene_count=1, render_profile='none', render_quality='preview',
            render_device='CPU', gpu='', threads=4, window_scenery=None,
            door_physics_worker_config=None, stage_timeout_s=1800)
        # Fixed historical seed/index is declared before launch, never resampled.
        result.update(seed=seed, rplan_index=config['rplan_index'],
                      rplan_sampling=config['rplan_sampling'])
        save(root / 'selection.json', result)
        prior_usage = Path(load(TEMPLATE / 'runtime.json')['usage_ledger'])
        inputs[str(prior_usage)] = digest(prior_usage)
        shutil.copy2(prior_usage, config['usage_ledger'])
        from stable_pipeline import child_environment
        environment = child_environment(config, root)
        environment.update(PYTHONPATH=str(SOURCE), CUDA_VISIBLE_DEVICES='',
                           PYTHONDONTWRITEBYTECODE='1', PYTHONUNBUFFERED='1')
        os.environ.clear()
        os.environ.update(environment)
        save(root / 'initial_runtime.json', config)
        save(root / 'historical_input_sha256.json', inputs)
        stage('01_fresh_layout', [generation_python,
            str(SOURCE / 'scripts/internal/scene_generation/run_rhg_v16_21p_procedural_pure_scene_generation.py'),
            '--out-root', config['baseline_root'], '--scene-count', '1',
            '--blender', config['blender'], '--skip-render', '--layout-shell',
            '--diagnostic-view-set', 'none', '--no-astra-cache', '--env-file',
            str(SOURCE / 'configs/no_external_api.env')], 1800)
        shell = Path(config['baseline_root']) / 'fullhome_asset_v16_000'
        manifest = load(shell / 'composition_manifest.runtime.json')
        roles = module('frozen_role_helper', ROLE_HELPER)
        roles.REPO = SOURCE
        roles.CODE = SOURCE / 'scripts/internal/scene_generation/real_assets'
        domains, derivation = roles.request_for_layout(shell, load(TEMPLATE / 'request.json'), config)
        projection = module('frozen_request_projection', PROJECT_HELPER)
        request, projection_receipt = projection.scene_request(manifest, domains)
        from bind_fixed_layout import semantic_key
        request, semantic_receipt = project_with_semantic_preservation(
            manifest, request, semantic_key=semantic_key)
        save(root / 'request.json', request)
        save(root / 'request_derivation.json', derivation)
        save(root / 'request_projection.json', projection_receipt)
        save(root / 'request_semantic_audit.json', semantic_receipt)
        config['joint_request'] = str(root / 'request.json')
        save(root / 'runtime_template.json', config)
        chain_config = dict(schema='rhg.frontier-chain-config.v1',
            manifest=str(shell / 'composition_manifest.runtime.json'),
            request=str(root / 'request.json'), generation=dict(
                runtime_template=str(root / 'runtime_template.json'),
                command=[generation_python, '{source_root}/scripts/run_generate_scene.py',
                    '--config', '{runtime}', '--joint-request', '{request}',
                    '--out-root', '{attempt_dir}/generated', '--stop-after', 'task-plan'],
                manifest_output='generated/fullhome_asset_v16_000/composition_manifest.runtime.json',
                timeout_s=7200))
        save(root / 'chain_config.json', chain_config)
        preflight = run_chain(root / 'chain_config.json', root / 'audit')
        if preflight['status'] != 'preflight_complete':
            raise RuntimeError('New chain preflight blocked; inspect audit/result.json')
        chain = run_chain(root / 'chain_config.json', root / 'chain', execute=True)
        result['chain_status'] = chain['status']
        if chain['status'] != 'generation_completed_pending_native_validation':
            raise RuntimeError('New chain generation/contract blocked; inspect chain/result.json')
        scene = root / 'chain/attempt_01/generated/fullhome_asset_v16_000'
        report = load(scene.parent / 'run_report.json')
        actual = load(scene / 'composition_manifest.runtime.json')
        episode = load(scene / 'BenchmarkEpisode.v16.json')
        plan = load(scene / 'generation_task_plan.json')
        if (report.get('requested_scope_passed') is not True
                or episode['task_spec'].get('task_kind') != 'scene_generation'
                or plan.get('passed') is not True or plan.get('scope') != 'no_robot_task_requested'
                or {e['entity_id'] for e in actual['entities']} != {e['entity_id'] for e in manifest['entities']}
                or actual['floor_plan'] != manifest['floor_plan']):
            raise ValueError('Native full-house generation scope/inventory failed')
        meshes = root / 'geometry/physical_meshes.json.gz'
        meshes.parent.mkdir()
        stage('03_saved_meshes', [config['blender'], '--background', '--python-exit-code', '1',
            '--python', str(SOURCE / 'packages/sim2real/geometry/export_meshes.py'),
            '--', '--scene', str(scene), '--out', str(meshes)], 1800)
        artifacts = [meshes, scene / 'composition_manifest.runtime.json',
            scene / 'SceneManifest.v16.json', scene / 'BenchmarkEpisode.v16.json',
            scene / (actual['scene_id'] + '.blend')]
        result.update(passed=True, generated_scene=str(scene),
            full_entity_count=len(actual['entities']), room_count=len(actual['floor_plan']['rooms']),
            output_artifacts_sha256={str(path): digest(path) for path in artifacts},
            acceptance_scope='real_furnished_house_native_manifest_contract_and_saved_mesh_export_only')
    except Exception as error:
        result.update(error_type=type(error).__name__, error=str(error))
    finally:
        result['historical_inputs_unchanged'] = all(Path(path).is_file() and digest(path) == sha
                                                   for path, sha in inputs.items())
        result['base_identity_after'] = base_identity()
        if not result['historical_inputs_unchanged'] or not result['base_identity_after']['passed']:
            result['passed'] = False
        result['elapsed_s'] = round(time.monotonic() - started, 3)
        save(root / 'real_house_result.json', result)
    print(json.dumps(result), flush=True)
    return 0 if result['passed'] else 1


if __name__ == '__main__':
    raise SystemExit(main())