File size: 26,985 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
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
#!/usr/bin/env python3
"""Render an already copied, packed scene on an explicitly idle Linux GPU.

Run with a configured Python on the target host. No staging, SSH, scene saving,
texture substitution or GPU-process termination is performed. result.json binds
the native packing readback, live GPU XML, bounded command and rendered files.
Rendering completion is independent of sampled visibility coverage. Neither
one establishes appearance, physics or whole-task acceptance.
"""
from __future__ import annotations

import argparse
from contextlib import contextmanager
from datetime import datetime, timezone
import hashlib
import json
import math
import os
from pathlib import Path, PurePosixPath
import re
import shutil
import signal
import stat
import subprocess
import sys
import time
import xml.etree.ElementTree as ET

ROOT = Path(__file__).resolve().parents[1]
sys.dont_write_bytecode = True
if __package__:
    from .. import process_control, visibility_plan
else:
    sys.path.insert(0, str(ROOT))
    import process_control
    import visibility_plan

execute_command = process_control.execute_command
EVIDENCE_NAME = 'wholehouse_visibility_evidence.json'


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 load(path):
    value = json.loads(Path(path).read_text(encoding='utf-8'))
    json.dumps(value, allow_nan=False)
    if not isinstance(value, dict):
        raise ValueError('Require a JSON object: ' + str(path))
    return value


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


def snapshot(scene):
    files = {}
    for path in sorted(Path(scene).rglob('*')):
        if path.is_symlink():
            raise ValueError('Copied scene cannot contain symbolic links: ' + str(path))
        if path.is_file():
            files[path.relative_to(scene).as_posix()] = digest(path)
    return files


def _sha(value):
    return isinstance(value, str) and re.fullmatch(r'[0-9a-f]{64}', value) is not None


def verify_source(scene, before):
    """Use native reopen evidence, including its content-bound image readbacks."""
    def bound(name):
        value = load(scene / name)
        if name not in before or digest(scene / name) != before[name]:
            raise ValueError('Source metadata changed while reading: ' + name)
        return value

    manifest = bound('composition_manifest.runtime.json')
    scene_id = manifest.get('scene_id')
    if (not isinstance(scene_id, str) or not scene_id or scene_id in ('.', '..')
            or Path(scene_id).name != scene_id or '\\' in scene_id):
        raise ValueError('Require a safe native scene_id')
    blend = scene / (scene_id + '.blend')
    blend_sha = before.get(blend.name)
    if not _sha(blend_sha):
        raise ValueError('Saved source blend is missing')
    audit = bound('real_asset_import_audit.json')
    verification = bound('saved_blend_verification.json')
    if (verification.get('passed') is not True or verification.get('failures') != []
            or verification.get('scene_id') != scene_id
            or verification.get('blend_sha256') != blend_sha
            or verification.get('import_audit_sha256') != before['real_asset_import_audit.json']
            or audit.get('passed') is not True or audit.get('scene_id') != scene_id):
        raise ValueError('Native saved-blend verification does not bind the copied source bytes')
    rows = manifest.get('entities')
    if (not isinstance(rows, list) or not rows
            or type(verification.get('entity_count')) is not int
            or verification['entity_count'] != len(rows)):
        raise ValueError('Native entity readback does not cover the manifest')
    packed, active = audit.get('packed_image_resources'), verification.get('active_resources')
    count = audit.get('packed_image_count')
    if (type(count) is not int or count < 0 or not isinstance(packed, list)
            or count != len(packed) or not isinstance(active, list) or len(active) != count):
        raise ValueError('Packed image count/list and active image readback must be present and agree')
    expected = {}
    for resource in packed:
        name = resource.get('image_name')
        if (not isinstance(name, str) or not name or name in expected
                or not _sha(resource.get('packed_sha256'))
                or type(resource.get('packed_bytes')) is not int or resource['packed_bytes'] <= 0):
            raise ValueError('Invalid packed image metadata')
        expected[name] = resource['packed_sha256']
    seen = set()
    for resource in active:
        name, size = resource.get('image_name'), resource.get('size')
        if (not isinstance(name, str) or name in seen or name not in expected
                or resource.get('packed') is not True
                or resource.get('packed_sha256') != expected[name]
                or not isinstance(size, list) or len(size) != 2
                or any(type(n) is not int or n <= 0 for n in size)):
            raise ValueError('Active images are not verified packed byte-for-byte')
        seen.add(name)
    manifest_sha = before['composition_manifest.runtime.json']
    for key, expected_sha in (('source_sha256', blend_sha), ('blend_sha256', blend_sha),
                              ('source_manifest_sha256', manifest_sha)):
        if manifest.get(key) is not None and manifest[key] != expected_sha:
            raise ValueError('Stale manifest binding: ' + key)
    return dict(manifest=manifest, blend=blend, blend_sha256=blend_sha,
        manifest_sha256=manifest_sha, packing=dict(passed=True, packed_image_count=count,
            saved_blend_verification_sha256=before['saved_blend_verification.json'],
            import_audit_sha256=before['real_asset_import_audit.json'],
            packed_image_sha256=expected, scope='native_reopen_readback_bound_to_saved_blend_and_import_audit'))


def require_linux_supervisor():
    if (not sys.platform.startswith('linux')
            or not callable(getattr(os, 'pidfd_open', None))
            or not callable(getattr(signal, 'pidfd_send_signal', None))
            or not Path('/proc/self/stat').is_file()):
        raise RuntimeError('Run with Python on Linux with /proc and pidfd support')


def idle_gpu(xml, uuid):
    root = ET.fromstring(xml)
    selected = [gpu for gpu in root.findall('gpu') if gpu.findtext('uuid') == uuid]
    if root.tag != 'nvidia_smi_log' or len(selected) != 1:
        raise ValueError('Selected GPU UUID is missing or ambiguous in live nvidia-smi XML')
    gpu = selected[0]

    def number(path, unit):
        value = gpu.findtext(path, '').strip()
        matched = re.fullmatch(r'([0-9]+(?:\.[0-9]+)?)\s+' + re.escape(unit), value)
        if matched is None:
            raise ValueError('Unavailable GPU measurement: ' + path)
        return float(matched[1])

    memory = number('fb_memory_usage/used', 'MiB')
    utilization = number('utilization/gpu_util', '%')
    processes = gpu.find('processes')
    if (memory >= 100 or utilization != 0 or processes is None or len(processes)
            or (processes.text or '').strip() or gpu.findall('.//process_info')):
        raise ValueError('Selected GPU is occupied or process evidence is unavailable; no render launched')
    return dict(uuid=uuid, memory_used_mib=memory, utilization_percent=utilization,
        process_count=0, idle=True, observed_at_utc=datetime.now(timezone.utc).isoformat())


def isolated_environment(output, uuid):
    overrides = dict(CUDA_VISIBLE_DEVICES=uuid, CUDA_DEVICE_ORDER='PCI_BUS_ID',
        PYTHONNOUSERSITE='1', PYTHONDONTWRITEBYTECODE='1', PYTHONUNBUFFERED='1',
        PYTHONPATH=str(ROOT), OMP_NUM_THREADS='8', OPENBLAS_NUM_THREADS='1', MKL_NUM_THREADS='1')
    for key, relative in dict(TMPDIR='tmp', TMP='tmp', TEMP='tmp',
            XDG_CACHE_HOME='cache', XDG_CONFIG_HOME='config', XDG_DATA_HOME='data',
            XDG_STATE_HOME='state', CUDA_CACHE_PATH='cuda',
            BLENDER_USER_CONFIG='blender/config', BLENDER_USER_SCRIPTS='blender/scripts',
            BLENDER_USER_DATAFILES='blender/datafiles').items():
        path = output / 'environment' / relative
        path.mkdir(parents=True, exist_ok=True)
        overrides[key] = str(path)
    return overrides


def cache_snapshot(directory):
    directory = Path(directory).absolute()
    if any(path.is_symlink() for path in (directory, *directory.parents)):
        raise ValueError('CUDA cache seed cannot contain symbolic links')
    if not directory.is_dir():
        raise ValueError('CUDA cache seed must be an existing directory')
    files = {}
    for path in sorted(directory.rglob('*')):
        mode = path.lstat().st_mode
        if stat.S_ISDIR(mode):
            continue
        if not stat.S_ISREG(mode):
            raise ValueError('CUDA cache seed permits only directories and regular files: ' + str(path))
        files[path.relative_to(directory).as_posix()] = digest(path)
    return files


def copy_cuda_cache(source, destination, receipt):
    # Byte provenance only; driver/compiler identity and cache hits are not certified.
    before = cache_snapshot(source)
    receipt['files_sha256'] = before
    for name in before:
        target = destination / name
        target.parent.mkdir(parents=True, exist_ok=True)
        shutil.copyfile(source / name, target, follow_symlinks=False)
    receipt['source_unchanged'] = cache_snapshot(source) == before
    if not receipt['source_unchanged'] or cache_snapshot(destination) != before:
        raise ValueError('CUDA cache seed or copied bytes changed during copying')
    receipt['copied'] = True


@contextmanager
def environment_scope(overrides):
    previous = dict(os.environ)
    try:
        os.environ.pop('PYTHONHOME', None)
        os.environ.pop('PYTHONSTARTUP', None)
        os.environ.update(overrides)
        yield
    finally:
        os.environ.clear()
        os.environ.update(previous)


def render_profile(name):
    if name == 'interior':
        return dict(visibility_plan.INTERIOR_RENDER_PROFILE)
    if name == 'diagnostic':
        return dict(width=640, height=360, samples=8, denoise=False, time_budget_s=360.)
    raise ValueError('Unknown rendering profile: '+str(name))


def write_interior_contact_sheet(output, render_directory=None):
    from PIL import Image, ImageDraw
    output = Path(output)
    render_directory = Path(render_directory) if render_directory is not None else output/'render'
    evidence = load(render_directory/EVIDENCE_NAME)
    candidates = [view for view in evidence['views']
                if view['camera'].get('purpose') == 'interior_human_eye'
                and view['camera'].get('projection') == 'PERSP'
                and view['camera'].get('required') is True]
    def anchor_score(view):
        pixels = view.get('target_pixels', {})
        anchors = view['camera'].get('focus_entity_ids', [])
        # Prefer seeing every main anchor, then useful measured image area.
        # This selection is for human review, never appearance qualification.
        return (sum(pixels.get(eid, 0) >= 128 for eid in anchors),
                sum(min(pixels.get(eid, 0), 1280*720*.3) for eid in anchors))
    selected = [max((v for v in candidates if v['camera']['room_ids'][0] == room),
                    key=anchor_score)
                for room in sorted({v['camera']['room_ids'][0] for v in candidates})]
    if not selected:
        raise ValueError('No primary room perspectives available for contact sheet')
    selected.sort(key=lambda view: view['camera']['room_ids'][0])
    columns = min(2, len(selected))
    sheet = Image.new('RGB', (columns*640, math.ceil(len(selected)/columns)*392), '#202428')
    draw = ImageDraw.Draw(sheet)
    for index, view in enumerate(selected):
        room = view['camera']['room_ids'][0]
        x, y = index % columns*640, index//columns*392
        draw.text((x+12, y+10), room.replace('_', ' ').title(), fill='white')
        image_path = (render_directory/view['image']['path']).resolve()
        image_path.relative_to(output.resolve())
        if view['image'].get('sha256') not in (None, digest(image_path)):
            raise ValueError('Selected image differs from measured receipt')
        with Image.open(image_path) as image:
            sheet.paste(image.convert('RGB').resize((640, 360), Image.Resampling.LANCZOS), (x, y+32))
    path = output/'interior_contact_sheet.png'
    sheet.save(path)
    result = dict(schema='rhg.selected-room-views.v1', path=path.name, sha256=digest(path),
                source_sha256=evidence.get('source_sha256'),
                source_manifest_sha256=evidence.get('source_manifest_sha256'),
                appearance_qualified=False, whole_task_acceptance=False,
                room_ids=[v['camera']['room_ids'][0] for v in selected],
                selected_camera_ids=[v['camera_id'] for v in selected],
                selection_method='measured_main_anchor_presence_then_capped_pixels',
                selected_images=[dict(room_id=v['camera']['room_ids'][0],
                    camera_id=v['camera_id'],
                    path=(render_directory/v['image']['path']).resolve().relative_to(output.resolve()).as_posix(),
                    sha256=digest(render_directory/v['image']['path']),
                    anchor_pixels={eid: v.get('target_pixels', {}).get(eid, 0)
                                   for eid in v['camera'].get('focus_entity_ids', [])}) for v in selected])
    save(output/'selectedroomviews.json', result)
    return result


def _plan_matches(plan, expected):
    expected = json.loads(json.dumps(expected, allow_nan=False))
    cameras = plan.get('cameras')
    if isinstance(cameras, list) and len(cameras) == len(expected['cameras']):
        for actual, wanted in zip(cameras, expected['cameras']):
            scale = actual.get('ortho_scale') if isinstance(actual, dict) else None
            reference = wanted.get('ortho_scale')
            # Python 3.12+ compensated sum changes camera fitting by one ULP
            # versus the system Python 3.10 used by the independent verifier.
            if (wanted.get('projection') == 'ORTHO' and type(reference) is float
                    and type(scale) is float and math.isfinite(scale)
                    and scale in (math.nextafter(reference, -math.inf),
                                  math.nextafter(reference, math.inf))):
                wanted['ortho_scale'] = scale
    return plan == expected


def verify_render(output, source, profile='diagnostic'):
    render = output / 'render'
    evidence = load(render / EVIDENCE_NAME)
    plan = load(render / 'visibility_plan.json')
    settings = render_profile(profile)
    expected = visibility_plan.build_visibility_plan(dict(source['manifest'],
        source_sha256=source['blend_sha256'], source_manifest_sha256=source['manifest_sha256']),
        width=settings['width'], height=settings['height'])
    if not _plan_matches(plan, expected):
        raise ValueError('Rendered camera plan does not bind the copied scene and requested resolution')
    execution = evidence.get('execution') or {}
    if (type(evidence.get('passed')) is not bool
            or evidence.get('render_completed') is not True or evidence.get('source_unchanged') is not True
            or evidence.get('source_sha256_after') != source['blend_sha256']
            or execution.get('device') != 'GPU' or execution.get('backend') != 'CUDA'
            or execution.get('samples') != settings['samples']
            or (profile == 'interior' and execution.get('denoise') is not True)
            or not isinstance(execution.get('devices'), list)
            or not execution['devices']
            or any(not isinstance(name, str) or not name for name in execution['devices'])
            or any(evidence.get(key) is not False for key in ('physical_qualified', 'whole_task_acceptance'))):
        raise ValueError('Incomplete source-bound CUDA rendering receipt')
    files = evidence.get('files_sha256')
    if not isinstance(files, dict) or not files:
        raise ValueError('Rendered file hashes are missing')
    for name, sha in files.items():
        relative = PurePosixPath(name)
        path = render / relative
        if (not name or '\\' in name or relative.is_absolute() or '..' in relative.parts
                or not _sha(sha) or path.is_symlink() or render not in path.resolve().parents
                or not path.is_file() or digest(path) != sha):
            raise ValueError('Rendered artifact is missing, changed or escaped output: ' + str(name))
    # The renderer's `passed` describes target coverage. Recompute the audit
    # without that summary so occlusion cannot masquerade as execution failure.
    audit = visibility_plan.audit_visibility(plan, {k: v for k, v in evidence.items() if k != 'passed'})
    allowed_pending = {'room_pixel_coverage_incomplete', 'target_visibility_incomplete'}
    if (audit['errors'] or audit['missing_camera_ids']
            or set(audit['pending']) - allowed_pending or not evidence.get('views')):
        raise ValueError('Render evidence is invalid or required render views are incomplete: ' +
                         str(audit['errors'] + audit['pending']))
    if evidence['passed'] is not audit['passed'] or load(render / 'visibility_audit.json') != audit:
        raise ValueError('Saved visibility audit differs from independent receipt verification')
    return audit


def run(args):
    started = time.monotonic()
    scene, output = Path(args.scene).resolve(), Path(args.output).resolve()
    if (scene == output or scene in output.parents or output in scene.parents
            or output == ROOT / 'source' or ROOT / 'source' in output.parents):
        raise ValueError('Fresh render output must be isolated outside the source scene and source tree')
    output.mkdir(parents=True, exist_ok=False)
    result = dict(schema='rhg.remote-gpu-render.v1', passed=False, render_completed=False,
        source_unchanged=False, visibility_passed=False, appearance_qualified=False,
        physical_qualified=False, whole_task_acceptance=False, accepted_training_positive=False,
        scene=str(scene), output=str(output), gpu_uuid=args.gpu_uuid, artifact_sha256={})
    before, implementations, seed_source = None, {}, None
    try:
        profile = getattr(args, 'profile', 'diagnostic')
        settings = render_profile(profile)
        result['render_profile'] = dict(name=profile, **settings)
        if (type(args.timeout_s) not in (int, float) or not math.isfinite(args.timeout_s)
                or args.timeout_s <= 0):
            raise ValueError('timeout-s must be finite and positive')
        deadline = started + args.timeout_s
        if not isinstance(args.gpu_uuid, str) or not re.fullmatch(r'GPU-[A-Za-z0-9-]+', args.gpu_uuid):
            raise ValueError('Require an explicit physical GPU UUID')
        if not scene.is_dir():
            raise ValueError('Copied scene directory is missing')
        before = snapshot(scene)
        result['source_files_sha256'] = before
        source = verify_source(scene, before)
        result.update(packing_verification=source['packing'],
            source_manifest_sha256=source['manifest_sha256'], source_blend_sha256=source['blend_sha256'])
        blender, renderer = Path(args.blender).resolve(), Path(args.renderer).resolve()
        if not blender.is_file() or not os.access(blender, os.X_OK) or not renderer.is_file():
            raise ValueError('Require an executable Blender and an existing renderer script')
        implementations = {str(path): digest(path) for path in
            (Path(__file__).resolve(), Path(process_control.__file__).resolve(),
             Path(visibility_plan.__file__).resolve(), renderer, blender)}
        result['implementation_sha256'] = implementations
        require_linux_supervisor()
        result['environment'] = isolated_environment(output, args.gpu_uuid)
        if getattr(args, 'cuda_cache_seed', None) is not None:
            seed_source = Path(args.cuda_cache_seed).absolute()
            result['cache_seed'] = dict(source=str(seed_source), files_sha256={},
                                        copied=False, source_unchanged=False)
            if seed_source == output or seed_source in output.parents or output in seed_source.parents:
                raise ValueError('CUDA cache seed must be isolated outside the new output')
            copy_cuda_cache(seed_source, Path(result['environment']['CUDA_CACHE_PATH']),
                            result['cache_seed'])
        command = [str(blender), '--background', '--threads', '8', '--python-exit-code', '1',
            '--python', str(renderer), '--', '--scene', str(scene), '--output', str(output / 'render'),
            '--device', 'GPU', '--gpu-backend', 'CUDA', '--width', str(settings['width']),
            '--height', str(settings['height']), '--samples', str(settings['samples']),
            '--denoise' if settings['denoise'] else '--no-denoise',
            '--time-budget-s', str(settings['time_budget_s'])]
        if snapshot(scene) != before:
            raise ValueError('Source changed before GPU preflight')
        remaining = deadline - time.monotonic()
        if remaining <= 0:
            raise TimeoutError('Render timeout exhausted before GPU preflight')
        probe = subprocess.run(['nvidia-smi', '-q', '-x'], capture_output=True, text=True,
                               check=True, timeout=min(15., remaining))
        (output / 'gpu_before.xml').write_text(probe.stdout)
        result['gpu_preflight'] = idle_gpu(probe.stdout, args.gpu_uuid)
        save(output / 'gpu_preflight.json', result['gpu_preflight'])
        remaining = deadline - time.monotonic()
        if remaining <= 0:
            raise TimeoutError('Render timeout exhausted before launch')
        with environment_scope(result['environment']):
            process = execute_command(command, output, output / 'render.log', remaining)
        result['command'] = process
        save(output / 'command.json', process)
        if (process.get('exit_code') != 0 or process.get('timed_out') is not False
                or process.get('cleanup_passed') is not True
                or (process.get('cleanup') or {}).get('complete') is not True):
            raise RuntimeError('Renderer failed, timed out or ownership cleanup was incomplete')
        audit = verify_render(output, source, profile=profile)
        save(output / 'render_verification.json', dict(schema='rhg.remote-render-verification.v1',
            passed=True, render_completed=True, visibility_passed=audit['passed'],
            coverage_audit=audit, appearance_qualified=False, physical_qualified=False,
            whole_task_acceptance=False))
        if profile == 'interior':
            result['interior_contact_sheet'] = write_interior_contact_sheet(output)
        result.update(passed=True, render_completed=True, visibility_passed=audit['passed'])
    except Exception as error:
        result.update(passed=False, error_type=type(error).__name__, error=str(error))
    finally:
        if seed_source is not None:
            try:
                result['cache_seed']['source_unchanged'] = (
                    cache_snapshot(seed_source) == result['cache_seed']['files_sha256'])
                if not result['cache_seed']['source_unchanged']:
                    raise ValueError('CUDA cache seed changed during execution')
            except Exception as error:
                result['cache_seed']['source_unchanged'] = False
                result.update(passed=False, error_type=type(error).__name__, error=str(error))
        try:
            after = snapshot(scene) if before is not None else None
            result['source_unchanged'] = before is not None and after == before
            if after is not None:
                result['source_files_sha256_after'] = after
                result['source_manifest_sha256_after'] = after.get('composition_manifest.runtime.json')
                if 'source' in locals():
                    result['source_blend_sha256_after'] = after.get(source['blend'].name)
            result['implementation_unchanged'] = all(Path(path).is_file() and digest(path) == sha
                                                       for path, sha in implementations.items())
            if before is not None and not result['source_unchanged']:
                raise ValueError('Original copied source bytes or inventory changed during rendering')
            if not result['implementation_unchanged']:
                raise ValueError('Renderer or supervisor implementation changed')
        except Exception as error:
            result.update(passed=False, error_type=type(error).__name__, error=str(error))
        try:
            result['artifact_sha256'] = {path.relative_to(output).as_posix(): digest(path)
                for path in sorted(output.rglob('*')) if path.is_file()
                and 'environment' not in path.relative_to(output).parts and path.name != 'result.json'}
        except Exception as error:
            result.update(passed=False, error_type=type(error).__name__, error=str(error))
        if not result['source_unchanged'] or not result.get('implementation_unchanged'):
            result['passed'] = False
        if time.monotonic() - started > getattr(args, 'timeout_s', 0):
            result.update(passed=False, error_type='TimeoutError', error='Render runner exceeded timeout-s')
        result['elapsed_s'] = round(time.monotonic() - started, 3)
        save(output / 'result.json', result)
    return result


def parse_args(argv=None):
    parser = argparse.ArgumentParser(description=__doc__)
    for name in ('scene', 'output', 'blender'):
        parser.add_argument('--' + name, type=Path, required=True)
    parser.add_argument('--gpu-uuid', required=True)
    parser.add_argument('--profile', choices=('interior', 'diagnostic'), default='interior')
    parser.add_argument('--timeout-s', type=float, default=900.)
    parser.add_argument('--renderer', type=Path, default=Path(__file__).with_name('render_wholehouse.py'))
    parser.add_argument('--cuda-cache-seed', type=Path,
        help='Copy a completed raw CUDA cache into the new private cache; records byte provenance only')
    return parser.parse_args(argv)


def main(argv=None):
    try:
        result = run(parse_args(argv))
    except (ValueError, OSError) as error:
        result = dict(passed=False, error_type=type(error).__name__, error=str(error))
    print(json.dumps(result, allow_nan=False), flush=True)
    return 0 if result['passed'] else 1


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