File size: 16,353 Bytes
870b85a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3f15e9f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
870b85a
 
 
 
 
3f15e9f
870b85a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3f15e9f
 
 
 
 
 
 
 
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
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
"""Native adapter and explicit wholehouse launcher; default is dry-run."""
from __future__ import annotations

import argparse
import hashlib
import json
import math
import os
from pathlib import Path
import shutil
import sys

ROOT = Path(__file__).resolve().parents[1]
EVAL = Path(os.environ.get('RHG_EVAL_ROOT', ROOT / 'runs'))
PYTHON = Path(os.environ.get('RHG_PYTHON', sys.executable))
BLENDER = Path(os.environ.get('RHG_BLENDER', 'blender'))


def load(path):
    return json.loads(Path(path).read_text())


def save(path, value):
    path = Path(path)
    path.parent.mkdir(parents=True, exist_ok=True)
    temporary = path.with_suffix(path.suffix + '.tmp')
    temporary.write_text(json.dumps(value, indent=2, sort_keys=True) + '\n')
    temporary.replace(path)


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


def runtime_environment(root, *, native=False):
    root = Path(root).resolve()
    environment = dict(os.environ)
    for key, relative in dict(TMPDIR='tmp', TMP='tmp', TEMP='tmp',
            XDG_CACHE_HOME='user/cache', XDG_CONFIG_HOME='user/config',
            XDG_DATA_HOME='user/data', XDG_STATE_HOME='user/state',
            CUDA_CACHE_PATH='user/cuda', PYTHONPYCACHEPREFIX='user/pycache',
            MPLCONFIGDIR='user/matplotlib', PIP_CACHE_DIR='user/pip',
            NUMBA_CACHE_DIR='user/numba', HF_HOME='user/huggingface',
            TORCH_HOME='user/torch', BLENDER_USER_CONFIG='user/blender/config',
            BLENDER_USER_SCRIPTS='user/blender/scripts',
            BLENDER_USER_DATAFILES='user/blender/datafiles').items():
        path = root / relative
        path.mkdir(parents=True, exist_ok=True)
        environment[key] = str(path)
    environment.update(PYTHONNOUSERSITE='1', PYTHONDONTWRITEBYTECODE='1',
        PYTHONUNBUFFERED='1', OMP_NUM_THREADS='12', OPENBLAS_NUM_THREADS='1',
        MKL_NUM_THREADS='1', NUMEXPR_NUM_THREADS='12',
        PYTHONPATH=os.pathsep.join(str(root / path) for path in (
            ('source', 'inputs/native_site') if native else
            ('runtime_site', 'supervisor_site', 'source'))))
    environment.pop('PYTHONHOME', None)
    return environment


def native_commands(source, runtime, request, output):
    source, output = Path(source), Path(output)
    # The supervisor can use a small system Python; native assembly needs the
    # explicitly prepared case interpreter and Blender, with their dependencies.
    settings = load(runtime) if Path(runtime).is_file() else {}
    python = settings.get('python') or str(PYTHON)
    blender = settings.get('blender') or str(BLENDER)
    code = source / 'scripts/internal/scene_generation/real_assets'
    scene = output / 'fullhome_asset_v16_000'
    return [[str(python), '-B', str(source / 'scripts/run_mainline_pipeline.py'),
             '--config', str(runtime), '--joint-request', str(request),
             '--out-root', str(output), '--stop-after', 'assemble']] + [
        [str(blender), '--background', '--threads', '12', '--python-exit-code', '1',
         '--python', str(code / script), '--', '--scene', str(scene)]
        for script in ('verify_saved_blend.py', 'verify_metric_layout.py', 'verify_scene_geometry.py')]


def seed_material_cache(source, warm, destination):
    source, warm, destination = Path(source), Path(warm), Path(destination)
    implementation = source / 'scripts/internal/scene_generation/real_assets/structural_material_selection.py'
    seeded = []
    for receipt in sorted(warm.glob('structural_material_catalog_*.receipt.json')):
        value = load(receipt)
        if value.get('identity', {}).get('implementation_sha256') != digest(implementation):
            continue
        catalog = Path(value['catalog_path'])
        if digest(catalog) != value['catalog_sha256']:
            raise ValueError('Historical material cache bytes changed: ' + str(catalog))
        destination.mkdir(parents=True, exist_ok=True)
        copied = destination / catalog.name
        if copied.exists() and digest(copied) != value['catalog_sha256']:
            raise ValueError('Destination material cache bytes changed: ' + str(copied))
        if not copied.exists():
            shutil.copy2(catalog, copied)
        value['catalog_path'] = str(copied)
        save(destination / receipt.name, value)
        seeded.append(dict(source_receipt=str(receipt), source_receipt_sha256=digest(receipt),
                           catalog_sha256=value['catalog_sha256'], destination=str(copied)))
    return dict(seeded=seeded, native_cache_validation_retained=True,
                identity_and_source_stats_unchanged=True)


def seed_runtime_material_cache(source, runtime, base_warm=None):
    """Retain standard seed validation and optionally warm an internal case retry."""
    if runtime.get('artifact_cache_root'):
        destination = Path(runtime['artifact_cache_root']).resolve() / 'material_catalog'
        destination.mkdir(parents=True, exist_ok=True)
        # Native prepare_material_catalog owns its lock, source validation and
        # publication. Never replace it with a scene's selected material state.
        return dict(seeded=[], shared_material_cache=str(destination),
                    native_cache_validation_retained=True)
    destination = Path(runtime['cache_root']).resolve() / 'structural_materials'
    warm_value = runtime.get('same_case_material_cache')
    warm = None
    if warm_value:
        if not runtime.get('generation_case_root'):
            raise ValueError('same_case_material_cache requires generation_case_root')
        case = Path(runtime['generation_case_root']).resolve()
        warm = Path(warm_value).resolve()
        if case not in warm.parents or case not in destination.parents:
            raise ValueError('Material retry cache and destination must stay inside the same generation case')
        if not warm.is_dir():
            raise ValueError('Same-case material retry cache is unavailable: ' + str(warm))
        # A receipt inside the case cannot smuggle an external catalogue into
        # this retry. seed_material_cache retains all existing native hashes.
        for receipt in warm.glob('structural_material_catalog_*.receipt.json'):
            if case not in receipt.resolve().parents:
                raise ValueError('Same-case material receipt resolves outside generation case')
            catalog = Path(load(receipt)['catalog_path']).resolve()
            if case not in catalog.parents or warm not in catalog.parents:
                raise ValueError('Same-case material catalogue resolves outside its warm cache')
    seeded = seed_material_cache(source, base_warm or ROOT / 'inputs/material_cache', destination)
    if warm is not None:
        extra = seed_material_cache(source, warm, destination)
        seeded['seeded'].extend(extra['seeded'])
        seeded['same_case_material_cache'] = str(warm)
        seeded['generation_case_root'] = str(case)
    return seeded


def seed_shell_geometry_reuse(runtime):
    """Copy shell readbacks only between attempts inside one generation case."""
    warm_value = runtime.get('same_case_shell_geometry_cache')
    if not warm_value:
        return dict(seeded=[])
    if not runtime.get('generation_case_root'):
        raise ValueError('same_case_shell_geometry_cache requires generation_case_root')
    case = Path(runtime['generation_case_root']).resolve()
    warm = Path(warm_value).resolve()
    destination = (Path(runtime['cache_root']) / 'shell_geometry_reuse').resolve()
    if case not in warm.parents or case not in destination.parents:
        raise ValueError('Shell geometry retry cache and destination must stay inside the same generation case')
    if not warm.is_dir():
        raise ValueError('Same-case shell geometry retry cache is unavailable: ' + str(warm))
    entries = sorted(warm.glob('*.json'))
    for entry in entries:
        target = destination / entry.name
        if case not in entry.resolve().parents or warm not in entry.resolve().parents:
            raise ValueError('Shell geometry cache entry resolves outside its warm cache')
        if case not in target.resolve().parents or destination not in target.resolve().parents:
            raise ValueError('Shell geometry cache destination resolves outside its cache')
        if target.exists() and digest(target) != digest(entry):
            raise ValueError('Shell geometry cache destination conflicts: ' + str(target))
    destination.mkdir(parents=True, exist_ok=True)
    for entry in entries:
        target = destination / entry.name
        if not target.exists():
            shutil.copy2(entry, target)
    return dict(seeded=[str(destination / entry.name) for entry in entries],
                same_case_shell_geometry_cache=str(warm), generation_case_root=str(case))


def prepare_native_runtime(runtime_path, runtime, output_parent, original_sha256):
    """Strip only adapter options after they have seeded this attempt's cache."""
    runtime_path, output_parent = Path(runtime_path), Path(output_parent)
    if digest(runtime_path) != original_sha256:
        raise ValueError('Adapter input runtime changed during material cache seeding')
    adapter_keys = {'same_case_shell_geometry_cache', 'generation_case_root', 'same_case_material_cache', 'native_source_root',
                    'artifact_cache_root', 'layout_recovery_budget', 'activation_negative_cache'}
    removed = sorted(adapter_keys & runtime.keys())
    native_path = runtime_path
    if removed:
        native_path = output_parent / 'native_runtime.json'
        if native_path.resolve() == runtime_path.resolve():
            raise ValueError('Sanitized native runtime cannot overwrite adapter input runtime')
        native = {key: value for key, value in runtime.items() if key not in adapter_keys}
        if runtime.get('artifact_cache_root'):
            native['structural_material_cache_root'] = str(
                Path(runtime['artifact_cache_root']).resolve() / 'material_catalog')
        save(native_path, native)
    provenance = dict(schema='rhg.native_runtime_adapter.v1',
        input_runtime_path=str(runtime_path.resolve()), input_runtime_sha256=original_sha256,
        native_runtime_path=str(native_path.resolve()), native_runtime_sha256=digest(native_path),
        removed_adapter_keys=removed, adapter_path=str(Path(__file__).resolve()),
        adapter_sha256=digest(__file__), original_runtime_preserved=True)
    save(output_parent / 'runtime_adapter_provenance.json', provenance)
    return native_path, provenance


def scope_passed(receipt, expected):
    return (receipt.get('exit_code') in expected and receipt.get('timed_out') is False
            and receipt.get('cleanup_passed') is True)


def native_assembly_timeout(runtime):
    inline = runtime.get('stage_timeout_s', 1800)
    if type(inline) not in (int, float) or not math.isfinite(inline) or inline <= 0:
        raise ValueError('stage_timeout_s must be finite and positive')
    # Assembly contains several individually bounded preparation/binding stages.
    return max(1800, inline * 3)


def native_stage_timeouts(runtime):
    from source.scripts.internal.scene_generation.real_assets.stage_checkpoint import subprocess_timeout
    # The metric stage opens Blender itself, then may reopen support twice.
    # Its supervisor must allow both attempts plus startup/hash/readback time.
    metric = max(subprocess_timeout('RHG_METRIC_REOPEN_STAGE_TIMEOUT_S'),
                 3 * subprocess_timeout('RHG_SUPPORT_REOPEN_TIMEOUT_S') + 600)
    return (native_assembly_timeout(runtime),
            subprocess_timeout('RHG_SAVED_REOPEN_STAGE_TIMEOUT_S'), metric,
            subprocess_timeout('RHG_SCENE_GEOMETRY_STAGE_TIMEOUT_S'))


def native(args):
    source = args.source.resolve()
    if source != ROOT / 'source':
        raise ValueError('Native execution requires this fusion/source')
    output = args.output.resolve()
    if ROOT not in output.parents or source in output.parents:
        raise ValueError('Native output must be inside fusion and outside source')
    output.parent.mkdir(parents=True, exist_ok=True)
    runtime_sha256 = digest(args.runtime)
    runtime = load(args.runtime)
    if runtime.get('native_source_root') and Path(runtime['native_source_root']).resolve()!=source:
        raise ValueError('Controller source root differs from executed native source')
    seed = seed_runtime_material_cache(source, runtime)
    save(output.parent / 'material_cache_seed.json', seed)
    shell_seed = seed_shell_geometry_reuse(runtime)
    if runtime.get('same_case_shell_geometry_cache'):
        save(output.parent / 'shell_geometry_reuse_seed.json', shell_seed)
    native_runtime, runtime_provenance = prepare_native_runtime(
        args.runtime, runtime, output.parent, runtime_sha256)
    sys.path.insert(0, str(ROOT))
    from process_control import execute_command
    os.environ.update(runtime_environment(ROOT, native=True))
    receipts = []
    stage_timeouts = native_stage_timeouts(runtime)
    files = (None, 'saved_blend_verification.json', 'metric_layout_verification.json',
             'independent_saved_geometry.json')
    for index, argv in enumerate(native_commands(source, native_runtime, args.request, output)):
        expected = (75,) if index == 0 else (0,)
        log = output.parent / ('native_stage_%02d.log' % index)
        receipt = execute_command(argv, source, log, stage_timeouts[index])
        receipt.update(expected_exit_codes=list(expected), scope_passed=scope_passed(receipt, expected))
        if files[index] is not None and receipt['scope_passed']:
            verification = output / 'fullhome_asset_v16_000' / files[index]
            receipt['verification_path'] = str(verification)
            receipt['scope_passed'] = verification.is_file() and load(verification).get('passed') is True
            if verification.is_file():
                receipt['verification_sha256'] = digest(verification)
        save(log.with_suffix('.receipt.json'), receipt)
        receipts.append(receipt)
        if not receipt['scope_passed']:
            break
    passed = len(receipts) == len(files) and all(row['scope_passed'] for row in receipts)
    save(output.parent / 'native_scope.json', dict(passed=passed, stages=receipts,
        scene=str(output / 'fullhome_asset_v16_000'), source_root=str(source),
        physics_executed=False, physical_qualified=False, whole_task_acceptance=False,
        runtime_adapter_provenance=runtime_provenance))
    return 0 if passed else 1


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    subparsers = parser.add_subparsers(dest='mode', required=True)
    adapter = subparsers.add_parser('native')
    for name in ('source', 'runtime', 'request', 'output'):
        adapter.add_argument('--' + name, required=True, type=Path)
    run = subparsers.add_parser('run')
    run.add_argument('--config', type=Path, default=ROOT / 'inputs/chain_config.json')
    run.add_argument('--output', type=Path, default=ROOT / 'runs/server_house_01')
    run.add_argument('--execute', action='store_true')
    args = parser.parse_args()
    if args.mode == 'native':
        return native(args)
    argv = [sys.executable, '-B', str(ROOT / 'wholehouse_pipeline.py'),
            '--config', str(args.config.resolve()), '--output', str(args.output.resolve()), '--execute']
    environment = runtime_environment(ROOT)
    if not args.execute:
        print(json.dumps(dict(argv=argv, cwd=str(ROOT), generation_started=False,
            environment={key: environment[key] for key in ('PYTHONPATH', 'TMPDIR', 'XDG_CACHE_HOME')}), indent=2))
        return 0
    import signal
    if not hasattr(os, 'pidfd_open') or not hasattr(signal, 'pidfd_send_signal'):
        raise RuntimeError('Supervisor requires pidfd support')
    if args.output.exists():
        raise FileExistsError('Refusing to reuse an existing output: ' + str(args.output))
    if '/Users/' in json.dumps(load(args.config)):
        raise ValueError('Server config contains a local-machine path')
    os.chdir(ROOT)
    os.execve(sys.executable, argv, environment)


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