"""Stage actual server inputs and metadata, then probe dependencies without generation.""" from __future__ import annotations import argparse import concurrent.futures import importlib.util import json import os from pathlib import Path import shutil import sqlite3 import subprocess import sys sys.path.insert(0, str(Path(__file__).resolve().parent)) from run_server_house import BLENDER, EVAL, PYTHON, ROOT, digest, load, runtime_environment, save, seed_material_cache AB = Path(os.environ.get('RHG_AB_WORKSPACE', EVAL / 'pipeline_ab')) WQZ = Path(os.environ.get('RHG_SOURCE_WORKSPACE', EVAL / 'source')) WARM = Path(os.environ.get('RHG_WARM_MATERIAL_CACHE', EVAL / 'verified_material_cache')) def build_config(root): root = Path(root) return dict(schema='rhg.frontier-chain-config.v1', manifest=str(root / 'inputs/layout/fullhome_asset_v16_000/composition_manifest.runtime.json'), request=str(root / 'inputs/request.json'), max_attempts=2, generation=dict(runtime_template=str(root / 'inputs/runtime_template.json'), command=[sys.executable, '-B', str(root / 'real_test/run_server_house.py'), 'native', '--source', '{source_root}', '--runtime', '{runtime}', '--request', '{request}', '--output', '{attempt_dir}/generated'], manifest_output='generated/fullhome_asset_v16_000/composition_manifest.runtime.json', timeout_s=2700), geometry_validation=dict(blender=str(BLENDER), timeout_s=900), repair_execution=dict(enabled=True, max_attempts=2, total_timeout_s=7200), wholehouse=dict(width=640, height=360, render=dict(command=[str(BLENDER), '--background', '--threads', '12', '--python-exit-code', '1', '--python', str(root / 'real_test/render_wholehouse.py'), '--', '--scene', '{scene}', '--output', '{evidence_dir}', '--plan', '{plan}', '--device', 'GPU', '--gpu-backend', 'CUDA', '--samples', '8', '--time-budget-s', '360'], timeout_s=720))) def build_standalone_runtime(template, root): runtime = dict(template) root = Path(root) / 'runtime/standalone_01' for key, relative in dict(out_root='generated', jobs_root='jobs', cache_root='cache', usage_ledger='usage.json', mdl_bake_cache='mdl-cache', cuda_kernel_cache_root='cuda-cache', baseline_root='layout').items(): runtime[key] = str(root / relative) return runtime def build_retry_runtime(template, root, name): if Path(name).name != name or not name.startswith('server_native_'): raise ValueError('Require a simple server_native_ run name') runtime = dict(template) run = Path(root) / 'runs' / name for key, relative in dict(out_root='generated', jobs_root='jobs', cache_root='cache', usage_ledger='usage.json', mdl_bake_cache='mdl-cache', cuda_kernel_cache_root='cuda-cache', baseline_root='layout').items(): runtime[key] = str(run / relative) return runtime def stage_native_retry(name): run = ROOT / 'runs' / name runtime = build_retry_runtime(load(ROOT / 'inputs/runtime_template.json'), ROOT, name) if run.exists(): raise FileExistsError('Refusing to reuse native retry directory: ' + str(run)) contract = prepared_pool_probe(runtime) if not contract['passed']: raise RuntimeError('Prepared pool probe failed: ' + contract['log']) run.mkdir(parents=True, exist_ok=False) copy_verified(ROOT / 'inputs/paired_original/usage.json', run / 'usage.json') copy_tree(ROOT / 'inputs/layout', run / 'layout') save(run / 'runtime.json', runtime) argv = [sys.executable, '-B', str(ROOT / 'real_test/run_server_house.py'), 'native', '--source', str(ROOT / 'source'), '--runtime', str(run / 'runtime.json'), '--request', str(ROOT / 'inputs/request.json'), '--output', str(run / 'generated')] save(run / 'launch_preflight.json', dict(passed=True, generation_started=False, argv=argv, runtime_sha256=digest(run / 'runtime.json'), initial_usage_sha256=digest(run / 'usage.json'), source_sha256=inventory(ROOT / 'source'), prepared_pool_probe=contract, initial_seed=runtime['seed'], initial_rplan_index=runtime['rplan_index'], preserved_failed_run=str(ROOT / 'runs/server_native_01'))) print(json.dumps(dict(argv=argv, runtime=str(run / 'runtime.json'), preflight=str(run / 'launch_preflight.json')), indent=2)) return 0 def copy_verified(source, destination): source, destination = Path(source), Path(destination) expected = digest(source) destination.parent.mkdir(parents=True, exist_ok=True) if destination.exists(): if digest(destination) != expected: raise ValueError('Staged input differs; refusing overwrite: ' + str(destination)) else: shutil.copy2(source, destination) if digest(destination) != expected or digest(source) != expected: raise ValueError('Input changed while staging: ' + str(source)) return dict(source=str(source), path=str(destination), sha256=expected, size_bytes=destination.stat().st_size, physically_copied=True) def copy_tree(source, destination): paths = [path for path in sorted(Path(source).rglob('*')) if path.is_file() and '__pycache__' not in path.parts and not path.name.endswith('.pyc')] with concurrent.futures.ThreadPoolExecutor(max_workers=8) as pool: return list(pool.map(lambda path: copy_verified(path, Path(destination) / path.relative_to(source)), paths)) def inventory(root): return {path.relative_to(root).as_posix(): digest(path) for path in sorted(Path(root).rglob('*')) if path.is_file() and '__pycache__' not in path.parts and not path.name.endswith('.pyc')} def compare(left, right): common = set(left) & set(right) return dict(common_files=len(common), matching_files=sum(left[k] == right[k] for k in common), changed_files=[k for k in sorted(common) if left[k] != right[k]], left_only=sorted(set(left) - set(right)), right_only=sorted(set(right) - set(left))) def probe(name, argv, environment): logs = ROOT / 'inputs/probes' logs.mkdir(parents=True, exist_ok=True) result = subprocess.run([str(x) for x in argv], cwd=ROOT, env=environment, capture_output=True, text=True, timeout=60) output = result.stdout + result.stderr (logs / (name + '.log')).write_text(output) return dict(name=name, argv=[str(x) for x in argv], exit_code=result.returncode, passed=result.returncode == 0, log=str(logs / (name + '.log'))) def check_sqlite(path): with sqlite3.connect('file:' + str(path) + '?mode=ro', uri=True) as connection: integrity = connection.execute('pragma quick_check').fetchone()[0] tables = {row[0] for row in connection.execute("select name from sqlite_master where type='table'")} count = None assets = {} if 'candidates' in tables: count = connection.execute('select count(*) from candidates').fetchone()[0] for raw, in connection.execute('select candidate_json from candidates'): row = json.loads(raw) for key, hash_key in (('runtime_path', 'runtime_sha256'), ('canonical_path', 'asset_sha256')): if row.get(key): assets[row[key]] = row.get(hash_key) missing = [name for name in assets if not Path(name).is_file()] receipt_path = Path(path).with_suffix('.receipt.json') receipt_passed = None if 'candidates' in tables: receipt_passed = (receipt_path.is_file() and load(receipt_path).get('schema') == 'rhg.prepared_asset_pool.v2' and load(receipt_path).get('sha256') == digest(path)) return dict(path=str(path), integrity=integrity, candidates=count, referenced_assets=len(assets), missing_assets=missing, asset_sha256_references=assets, receipt_path=str(receipt_path) if receipt_passed is not None else None, receipt_passed=receipt_passed, passed=integrity == 'ok' and not missing and receipt_passed is not False) def stage_pool_receipts(template): original = load(AB / 'inputs/runtime_template.json') return [copy_verified(Path(original[key]).with_suffix('.receipt.json'), Path(template[key]).with_suffix('.receipt.json')) for key in ('prepared_asset_pool', 'supplemental_prepared_pool')] def prepared_pool_probe(template): code = ROOT / 'source/scripts/internal/scene_generation/real_assets' helpers = ROOT / 'source/scripts/internal/scene_generation' program = "\n".join([ 'import json,sys', 'from pathlib import Path', 'sys.path.insert(0,' + repr(str(code)) + ')', 'from prepared_asset_pool import annotation_reference', 'from stage_checkpoint import HashMemo', 'from source_probe_contract import implementation_signature', 'from support_contact_cache import implementation_signature as support_signature', 'config=json.loads(Path(' + repr(str(ROOT / 'inputs/runtime_template.json')) + ').read_text())', 'memo=HashMemo()', '_,report=annotation_reference(config["prepared_asset_pool"],config,memo)', 'code=Path(' + repr(str(code)) + ')', 'signature=implementation_signature(code,Path(' + repr(str(helpers)) + '))', 'parent=json.loads(Path(config["prepared_asset_pool"]).with_suffix(".receipt.json").read_text())', 'for key in ("prepared_asset_pool","supplemental_prepared_pool"):', ' receipt=json.loads(Path(config[key]).with_suffix(".receipt.json").read_text())', ' assert memo.digest(config[key])==receipt["sha256"],key+" hash mismatch"', ' assert receipt["importer_signature"]==signature,key+" importer mismatch"', ' assert receipt["support_signature"]==support_signature(code,signature),key+" support mismatch"', ' assert receipt["blender_version"]=="5.2.1 LTS",key+" Blender mismatch"', ' if key=="supplemental_prepared_pool": assert receipt["parent_pool_sha256"]==parent["sha256"]', 'print(json.dumps(report,sort_keys=True))']) return probe('native_prepared_pool_contract', [PYTHON, '-B', '-c', program], runtime_environment(ROOT, native=True)) def finish_pool_receipts(): inputs = ROOT / 'inputs' template = load(inputs / 'runtime_template.json') copied = stage_pool_receipts(template) checks = [check_sqlite(Path(template[key])) for key in ('prepared_asset_pool', 'supplemental_prepared_pool', 'annotation_index')] contract = prepared_pool_probe(template) manifest = load(inputs / 'server_dependency_manifest.json') manifest['staged_files'] += copied manifest['probes'] = [p for p in manifest['probes'] if p['name'] != contract['name']] + [contract] manifest['prepared_pool_checks'] = checks manifest['passed'] = (all(p['passed'] for p in manifest['probes'] + checks) and not manifest['missing_dependencies'] and not manifest['material_source_stats_changed']) manifest['latest_native_attempt'] = dict(path=str(ROOT / 'runs/server_native_01/native_scope.json'), passed=False, exit_code=1, reason='Missing prepared SQLite sidecar receipts; staged and probed after failure.', automatic_retry=False) save(inputs / 'server_dependency_manifest.json', manifest) save(inputs / 'prepared_pool_receipts_verified.json', dict(passed=manifest['passed'], staged=copied, checks=checks, native_probe=contract, generation_started=False)) hashes = load(inputs / 'staged_sha256.json') for p in (inputs / 'server_dependency_manifest.json', inputs / 'prepared_pool_receipts_verified.json', inputs / 'probes/native_prepared_pool_contract.log', *(Path(row['path']) for row in copied)): hashes[p.relative_to(inputs).as_posix()] = digest(p) save(inputs / 'staged_sha256.json', hashes) print(json.dumps(dict(passed=manifest['passed'], probe=contract, receipt=str(inputs / 'prepared_pool_receipts_verified.json')), indent=2)) return 0 if manifest['passed'] else 1 def stage_provenance(): inputs = ROOT / 'inputs' records = copy_tree(AB / 'wqz', inputs / 'provenance/ab_wqz_code') records += copy_tree(WQZ / 'code', inputs / 'provenance/wqz_server_code') for name in ('EFFECTIVE-RUNTIME-r5.json', 'DEFAULT-CONFIG-READBACK.json', 'CLOSEOUT-r5.json'): records.append(copy_verified(WQZ / name, inputs / 'provenance/wqz_runtime' / name)) for name in ('selection.json', 'completion.json'): records.append(copy_verified(AB / name, inputs / 'provenance/ab' / name)) server_files = inventory(inputs / 'provenance/wqz_server_code') ab_files = inventory(inputs / 'provenance/ab_wqz_code') fused_files = inventory(ROOT / 'source') save(inputs / 'source_provenance.json', dict(actual_wqz_source=str(WQZ / 'code'), frozen_completed_ab_source=str(AB / 'wqz'), active_source=str(ROOT / 'source'), server_wqz_has_git_metadata=(WQZ / 'code/.git').exists(), local_published_head_context_only='956036262327d95edd188a5bcc4f8354d8c78a7b', note='Local published HEAD is context, not proof of this server snapshot identity.', server_wqz_inventory=server_files, frozen_ab_inventory=ab_files, server_vs_frozen_ab=compare(server_files, ab_files), frozen_ab_vs_fusion=compare(ab_files, fused_files))) save(inputs / 'source_copy_receipt.json', dict(passed=True, physically_copied_files=records)) return records def prepare(*, runtime_only=False): if not AB.is_dir() or not WQZ.is_dir(): raise FileNotFoundError('Configure RHG_AB_WORKSPACE and RHG_SOURCE_WORKSPACE') inputs = ROOT / 'inputs' inputs.mkdir(parents=True, exist_ok=True) records = copy_tree(AB / 'inputs', inputs / 'paired_original') selection = load(AB / 'selection.json') for name, expected in selection['same_input_sha256'].items(): if digest(inputs / 'paired_original' / name) != expected: raise ValueError('Paired input no longer matches completed A/B: ' + name) records += copy_tree(AB / 'inputs/layout', inputs / 'layout') for name in ('request.json', 'usage.json'): records.append(copy_verified(AB / 'inputs' / name, inputs / name)) records += copy_tree(AB / 'supervisor_site', ROOT / 'supervisor_site') template = load(AB / 'inputs/runtime_template.json') shared = [] small_keys = ('annotation_delivery_receipt', 'attribute_release', 'native_articulation_catalog', 'prepared_asset_pool', 'prepared_support_surfaces', 'prepared_floor_body_geometry', 'supplemental_prepared_pool', 'source_candidates', 'texture_decoder') for key in small_keys: if template.get(key): path = Path(template[key]) destination = inputs / 'runtime_data' / key / path.name records.append(copy_verified(path, destination)) template[key] = str(destination) records += stage_pool_receipts(template) for key in ('annotation_snapshot', 'annotation_index'): path = Path(template[key]) expected = template.get('annotation_sha256') if key == 'annotation_snapshot' else None actual = digest(path) if expected and actual != expected: raise ValueError('Annotation snapshot changed') shared.append(dict(key=key, path=str(path), sha256=actual, size_bytes=path.stat().st_size, policy='shared_existing_zhf_read_only_hash_pinned')) template.update(python=str(PYTHON), blender=str(BLENDER), baseline_root=str(inputs / 'layout'), joint_request=str(inputs / 'request.json'), usage_ledger=str(inputs / 'usage.json'), threads=12, render_profile='none', gpu='', render_device='CPU', rplan_seeds=os.environ.get( 'RHG_RPLAN_SEEDS', str(ROOT / 'source/configs/floorplans/rplan_production_16.json'))) for key, relative in dict(out_root='generated', jobs_root='jobs', cache_root='cache', mdl_bake_cache='mdl-cache', cuda_kernel_cache_root='cuda-cache').items(): template[key] = str(ROOT / 'runtime' / relative) for key, value in template.items(): values = value if isinstance(value, list) else [value] if key in ('out_root', 'jobs_root', 'cache_root', 'mdl_bake_cache', 'cuda_kernel_cache_root'): continue for item in values: if isinstance(item, str) and item.startswith('/mnt/') and not Path(item).exists(): raise FileNotFoundError(key + ': ' + item) if '/Users/' in json.dumps(template): raise ValueError('Local-machine path in runtime') save(inputs / 'runtime_template.json', template) save(inputs / 'chain_config.json', build_config(ROOT)) standalone = ROOT / 'runtime/standalone_01' if (standalone / 'generated').exists(): raise FileExistsError('Standalone output already exists; refusing runtime restaging') copy_verified(inputs / 'usage.json', standalone / 'usage.json') copy_tree(inputs / 'layout', standalone / 'layout') save(standalone / 'runtime.json', build_standalone_runtime(template, ROOT)) save(inputs / 'standalone_launch.json', dict(generation_started=False, argv=[sys.executable, '-B', str(ROOT / 'real_test/run_server_house.py'), 'native', '--source', str(ROOT / 'source'), '--runtime', str(standalone / 'runtime.json'), '--request', str(inputs / 'request.json'), '--output', str(standalone / 'generated')], environment={key: runtime_environment(ROOT)[key] for key in ('PYTHONPATH', 'TMPDIR', 'XDG_CACHE_HOME')})) seed = seed_material_cache(ROOT / 'source', WARM, inputs / 'material_cache') save(inputs / 'material_cache_seed.json', seed) if not seed['seeded']: raise ValueError('No compatible historical material catalog found') sql_checks = [check_sqlite(Path(template[key])) for key in ('prepared_asset_pool', 'supplemental_prepared_pool', 'annotation_index')] material_references = {} material_stats_changed = [] for item in seed['seeded']: catalog = Path(item['destination']) receipt = load(catalog.with_name(catalog.stem + '.receipt.json')) for name, expected in receipt.get('source_stats', {}).items(): try: stat = Path(name).stat() current = [stat.st_dev, stat.st_ino, stat.st_size, stat.st_mtime_ns, stat.st_ctime_ns] except OSError: current = None if current != expected: material_stats_changed.append(name) for name, evidence in receipt.get('verified_source_hash_evidence', {}).items(): material_references[name] = evidence save(inputs / 'shared_asset_references.json', dict( prepared_pools=sql_checks, material_references=material_references, material_source_stats_changed=material_stats_changed, policy='Existing zhf assets are read-only references; native validates hashes and stats on consumption.')) native_env, supervisor_env = runtime_environment(ROOT, native=True), runtime_environment(ROOT) native_imports = "import sys,numpy,shapely,PIL,ispc_texcomp; print(sys.version); print(numpy.__version__,shapely.__version__,PIL.__version__); print(sys.path)" supervisor_imports = "import os,signal,sys,numpy,shapely,manifold3d,process_control; from importlib.metadata import version; assert hasattr(os,'pidfd_open') and hasattr(signal,'pidfd_send_signal'); print(sys.version); print(numpy.__version__,shapely.__version__,version('manifold3d')); fd=os.pidfd_open(os.getpid()); os.close(fd)" probes = [probe('native_imports', [PYTHON, '-B', '-c', native_imports], native_env), probe('supervisor_imports', [sys.executable, '-B', '-c', supervisor_imports], supervisor_env), probe('native_mainline_help', [PYTHON, '-B', ROOT / 'source/scripts/run_mainline_pipeline.py', '--help'], native_env), probe('blender_version', [BLENDER, '--version'], native_env), prepared_pool_probe(template)] required_scripts = [ROOT / path for path in ( 'source/scripts/run_mainline_pipeline.py', 'source/scripts/run_generate_scene.py', 'source/scripts/run_frontier_generation.py', 'source/packages/sim2real/geometry/export_meshes.py', 'source/scripts/internal/scene_generation/real_assets/verify_saved_blend.py', 'source/scripts/internal/scene_generation/real_assets/verify_scene_geometry.py', 'source/scripts/internal/scene_generation/real_assets/ambientcg_evidence.json', 'real_test/render_wholehouse.py', 'wholehouse_pipeline.py')] missing = [str(path) for path in required_scripts if not path.is_file()] passed = (not missing and all(row['passed'] for row in probes + sql_checks) and not material_stats_changed) result = dict(schema='rhg.server-runtime-dependencies.v1', passed=passed, generation_started=False, source_root=str(ROOT / 'source'), seed=template['seed'], rplan_index=template['rplan_index'], threads=12, staged_files=records, shared_dependencies=shared, missing_dependencies=missing, probes=probes, material_source_stats_changed=material_stats_changed, required_script_sha256={str(path): digest(path) for path in required_scripts if path.is_file()}, active_config=str(inputs / 'chain_config.json'), launch_argv=[sys.executable, '-B', str(ROOT / 'real_test/run_server_house.py'), 'run', '--execute'], native_expected_exit_code=75, cache_validation_bypassed=False, runtime_has_local_machine_paths=False) result['standalone_runtime'] = str(standalone / 'runtime.json') result['standalone_launch_receipt'] = str(inputs / 'standalone_launch.json') result['geometry_backend_mesh_validation'] = 'Pending primary native crash containment; imports only tested here.' if not runtime_only: result['staged_files'] += stage_provenance() result['source_provenance_receipt'] = str(inputs / 'source_copy_receipt.json') result['source_provenance_staged'] = (inputs / 'source_copy_receipt.json').is_file() save(inputs / 'server_dependency_manifest.json', result) save(inputs / 'staged_sha256.json', {p.relative_to(inputs).as_posix(): digest(p) for p in inputs.rglob('*') if p.is_file() and p.name != 'staged_sha256.json'}) print(json.dumps({key: result[key] for key in ('passed', 'generation_started', 'active_config', 'missing_dependencies', 'material_source_stats_changed', 'probes', 'launch_argv')}, indent=2)) return 0 if passed else 1 if __name__ == '__main__': parser = argparse.ArgumentParser(description=__doc__) group = parser.add_mutually_exclusive_group() group.add_argument('--runtime-only', action='store_true') group.add_argument('--provenance-only', action='store_true') group.add_argument('--pool-receipts-only', action='store_true') group.add_argument('--stage-native-run') args = parser.parse_args() if args.stage_native_run: raise SystemExit(stage_native_retry(args.stage_native_run)) elif args.pool_receipts_only: raise SystemExit(finish_pool_receipts()) elif args.provenance_only: stage_provenance() print('Server WQZ and frozen A/B source copies verified') else: raise SystemExit(prepare(runtime_only=args.runtime_only))