"""Run a fresh, same-shell functional-children-first search followup. Default is dry-run: verify prepared inputs and print the proposed derivation. Example (the parent launches): python3 -B engine/real_test/run_search_followup.py \ --prepared-case /absolute/prepared/case_2026102401 \ --output /absolute/followups/seed2026102401/execution_followup_01 \ --blender /absolute/byte-identical/cached/blender --execute The new output contains request.json, runtime.json, chain_config.json, provenance, independent supervisor logs/receipt and execution/. No shell generation occurs. """ from __future__ import annotations import argparse import copy import json from pathlib import Path import shutil import sys if __package__: from . import run_three_houses as three else: sys.path.insert(0, str(Path(__file__).resolve().parents[1])) from real_test import run_three_houses as three ROOT = three.ROOT SCRIPT = Path(__file__).resolve() adapter = three.adapter WRITABLE_RUNTIME_KEYS = ('out_root', 'jobs_root', 'cache_root', 'usage_ledger', 'mdl_bake_cache', 'cuda_kernel_cache_root') OUTER_TIMEOUT_S = 8000 def derive_request(original): request = copy.deepcopy(original) search = request.setdefault('search', {}) if not isinstance(search, dict): raise ValueError('Original request.search must be an object') present = 'functional_children_first' in search before = search.get('functional_children_first') if before is True: raise ValueError('functional_children_first is already enabled; no new experiment') if present and type(before) is not bool: raise ValueError('Original functional_children_first must be boolean') search['functional_children_first'] = True restored = copy.deepcopy(request) if present: restored['search']['functional_children_first'] = before else: restored['search'].pop('functional_children_first') if 'search' not in original: restored.pop('search') if restored != original: raise ValueError('Followup must change only functional_children_first') return request, dict(changed_fields=['search.functional_children_first'], before_present=present, before=before, after=True, source_request_fingerprint=three.fingerprint(original), derived_request_fingerprint=three.fingerprint(request), all_other_fields_preserved=True) def derive_runtime(original, output, blender): isolated = three.case_runtime(original, output, original['seed']) runtime = copy.deepcopy(original) # case_runtime also resets sampling and policy fields. Use only its writable # paths so every seed, rplan value and the original shell remain unchanged. for key in WRITABLE_RUNTIME_KEYS: runtime[key] = isolated[key] runtime.update(joint_request=str(Path(output) / 'request.json'), blender=str(blender)) return runtime def verify_blender(runtime, override): original = Path(runtime['blender']).absolute() selected = Path(override).absolute() if override is not None else original original_sha = adapter.digest(original) selected_sha = original_sha if original == selected else adapter.digest(selected) if selected_sha != original_sha: raise ValueError('Blender override differs from original executable SHA256') return dict(original=str(original), selected=str(selected), original_sha256=original_sha, selected_sha256=selected_sha, same_sha256=True, dependency_version_checks='parent_supplied_cache_prevalidation') def validate_paths(case, output): if not case.is_absolute() or not output.is_absolute(): raise ValueError('--prepared-case and --output must be absolute paths') case, output = case.resolve(), output.resolve() if (case == output or case in output.parents or output in case.parents or output == ROOT or ROOT not in output.parents or ROOT / 'source' == output or ROOT / 'source' in output.parents): raise ValueError('Require a separate output inside the derivative, outside prepared case/source') if output.exists(): raise FileExistsError('Refusing existing followup output: ' + str(output)) return case, output def build_plan(args): case, output = validate_paths(Path(args.prepared_case), Path(args.output)) prepared_path = case / 'prepared.json' prepared = adapter.load(prepared_path) pins = dict(prepared.get('input_sha256', {})) if prepared.get('prepared') is not True or not pins: raise ValueError('Case must have a successful hash-bound prepared receipt') three.verify_hashes(pins) required = [case / name for name in ('runtime.json', 'request.json', 'chain_config.json', 'usage.json', 'request_semantic_audit.json')] shell = case / 'layout/fullhome_asset_v16_000' required.extend(shell / name for name in ('composition_manifest.runtime.json', 'SceneManifest.v16.json', 'blender_report.json', 'fullhome_asset_v16_000.blend')) for path in required: if str(path) not in pins: raise ValueError('Required prepared input is not hash-bound: ' + str(path)) for path in shell.rglob('*'): if path.is_symlink(): raise ValueError('Prepared shell cannot contain symlinks') if path.is_file() and str(path) not in pins: raise ValueError('Prepared shell contains an unbound file: ' + str(path)) runtime = adapter.load(case / 'runtime.json') seed = runtime.get('seed') if type(seed) is not int or seed not in three.SEEDS or seed != prepared.get('seed'): raise ValueError('Original runtime seed differs from prepared fixed seed') if Path(runtime['baseline_root']).resolve() != shell.parent: raise ValueError('Original baseline_root must reference this prepared case/layout') if runtime.get('scene_count') != 1 or Path(runtime['usage_ledger']).resolve() != case / 'usage.json': raise ValueError('Require one original shell and its private prepared usage ledger') manifest = adapter.load(shell / 'composition_manifest.runtime.json') request = adapter.load(case / 'request.json') entities = manifest.get('entities', []) rooms = manifest.get('floor_plan', {}).get('rooms', []) if len(entities) != 55 or len(rooms) != 7: raise ValueError('This experiment requires the original 7-room, 55-entity shell') ids = [row['entity_id'] for row in entities] if len(set(ids)) != 55: raise ValueError('Original shell requires 55 unique entity IDs') for key in ('entities', 'furniture'): values = [row['entity_id'] for row in request.get(key, [])] if len(values) != 55 or set(values) != set(ids): raise ValueError('Original request must preserve the complete shell entity inventory') audit = adapter.load(case / 'request_semantic_audit.json') if audit.get('passed') is not True or audit.get('checked_count') != 55: raise ValueError('Original semantic preservation audit must cover all 55 entities') derived, delta = derive_request(request) blender = verify_blender(runtime, args.blender) selected = Path(blender['selected']) isolated = derive_runtime(runtime, output, selected) config = copy.deepcopy(adapter.load(case / 'chain_config.json')) if Path(config['manifest']).resolve() != shell / 'composition_manifest.runtime.json': raise ValueError('Original config manifest does not bind the prepared shell') if (Path(config['request']).resolve() != case / 'request.json' or Path(config['generation']['runtime_template']).resolve() != case / 'runtime.json'): raise ValueError('Original config must bind this case request/runtime') geometry = config.get('geometry_validation') if not isinstance(geometry, dict) or geometry.get('enabled', True) is not True: raise ValueError('Strict geometry validation must remain enabled') config.update(request=str(output / 'request.json'), max_attempts=2, repair_execution=dict(enabled=True, max_attempts=2, total_timeout_s=7200)) config['generation'].update(runtime_template=str(output / 'runtime.json'), timeout_s=2700, command=[three.SUPERVISOR, '-B', str(SCRIPT), 'native', '--source', '{source_root}', '--runtime', '{runtime}', '--request', '{request}', '--output', '{attempt_dir}/generated', '--isolation', '{attempt_dir}/native_runtime', '--blender', str(selected), '--blender-sha256', blender['selected_sha256']]) config['geometry_validation']['blender'] = str(selected) pins[str(prepared_path)] = adapter.digest(prepared_path) pins[str(Path(blender['original']))] = blender['original_sha256'] pins[str(selected)] = blender['selected_sha256'] three.verify_hashes(pins) return dict(prepared_case=str(case), output=str(output), seed=seed, room_count=7, entity_count=55, request=derived, runtime=isolated, config=config, request_delta=delta, blender=blender, original_input_sha256=pins, shell_regenerated=False, same_prepared_shell=True, old_execution=str(case / 'execution'), outer_timeout_s=OUTER_TIMEOUT_S, command=[three.SUPERVISOR, '-B', str(ROOT / 'wholehouse_pipeline.py'), '--config', str(output / 'chain_config.json'), '--output', str(output / 'execution'), '--execute']) def native(args): selected = Path(args.blender).absolute() if adapter.digest(selected) != args.blender_sha256: raise ValueError('Selected Blender executable changed before native execution') if adapter.load(args.runtime).get('blender') != str(selected): raise ValueError('Native runtime Blender differs from bound executable') if args.output.exists(): raise FileExistsError('Refusing existing native followup output') isolated = three.case_environment(args.isolation, native=True) previous_blender, previous_environment = adapter.BLENDER, adapter.runtime_environment # Both substitutions are process-local; frozen adapter/source files stay intact. try: adapter.BLENDER = selected adapter.runtime_environment = lambda *unused, **kwargs: isolated with three.environment_scope(isolated): return adapter.native(args) finally: adapter.BLENDER, adapter.runtime_environment = previous_blender, previous_environment def run(args): plan = build_plan(args) if not args.execute: print(json.dumps(dict(execute=False, **plan), indent=2), flush=True) return 0 output = Path(plan['output']) output.mkdir(parents=True, exist_ok=False) result = dict(schema='rhg.same-shell-search-followup.v1', passed=False, seed=plan['seed'], prepared_case=plan['prepared_case'], output=str(output), shell_regenerated=False, same_prepared_shell=True, prepared_inputs_unchanged=False, physical_qualified=False, whole_task_acceptance=False) inputs = dict(plan['original_input_sha256']) for path in (SCRIPT, Path(three.__file__), Path(adapter.__file__), ROOT / 'wholehouse_pipeline.py'): if path.is_file(): inputs[str(path)] = adapter.digest(path) try: for name, value in (('request.json', plan['request']), ('runtime.json', plan['runtime']), ('chain_config.json', plan['config'])): adapter.save(output / name, value) inputs[str(output / name)] = adapter.digest(output / name) shutil.copyfile(Path(plan['prepared_case']) / 'usage.json', output / 'usage.json') if adapter.digest(output / 'usage.json') != inputs[str(Path(plan['prepared_case']) / 'usage.json')]: raise ValueError('Usage ledger copy differs from original prepared bytes') inputs[str(output / 'usage.json')] = adapter.digest(output / 'usage.json') provenance = dict(plan, derived_input_sha256={str(output / name): adapter.digest(output / name) for name in ('request.json', 'runtime.json', 'chain_config.json', 'usage.json')}) adapter.save(output / 'followup_provenance.json', provenance) inputs[str(output / 'followup_provenance.json')] = adapter.digest(output / 'followup_provenance.json') result['command'] = three.stage(output, 'supervisor', plan['command'], OUTER_TIMEOUT_S, three.case_environment(output / 'supervisor_runtime')) pipeline_path = output / 'execution/result.json' if pipeline_path.is_file(): result['pipeline_result'] = adapter.load(pipeline_path) result['pipeline_result_sha256'] = adapter.digest(pipeline_path) result['passed'] = (result['command']['scope_passed'] and result.get('pipeline_result', {}).get('wholehouse_evidence_complete') is True) except Exception as error: result.update(passed=False, error_type=type(error).__name__, error=str(error)) finally: try: three.verify_hashes(inputs) result['prepared_inputs_unchanged'] = True except Exception as error: result.update(passed=False, integrity_error=str(error)) result['input_sha256'] = inputs adapter.save(output / 'followup_result.json', result) print(json.dumps(result, indent=2), flush=True) return 0 if result['passed'] else 1 def main(argv=None): argv = list(sys.argv[1:] if argv is None else argv) parser = argparse.ArgumentParser(description=__doc__) if argv and argv[0] == 'native': for name in ('source', 'runtime', 'request', 'output', 'isolation', 'blender'): parser.add_argument('--' + name, required=True, type=Path) parser.add_argument('--blender-sha256', required=True) return native(parser.parse_args(argv[1:])) parser.add_argument('--prepared-case', type=Path, required=True) parser.add_argument('--output', type=Path, required=True) parser.add_argument('--blender', type=Path, help='Optional cached executable; its SHA256 must match the original runtime Blender') parser.add_argument('--execute', action='store_true') return run(parser.parse_args(argv)) if __name__ == '__main__': raise SystemExit(main())