"""Fork isolated native replays from immutable, preloaded input/style data.""" from __future__ import annotations import argparse import hashlib import importlib.util import json import os from pathlib import Path import socket import sys import tempfile import time import traceback ROOT = Path(__file__).resolve().parents[1] def digest(path): return hashlib.sha256(Path(path).read_bytes()).hexdigest() class FrozenCache: def __init__(self): self.hashes = {} self.values = {} self.by_digest = {} def pin(self, path): path = str(Path(path).resolve()) data = Path(path).read_bytes() sha = hashlib.sha256(data).hexdigest() if path in self.hashes and self.hashes[path] != sha: raise ValueError('Cached input changed: ' + path) self.hashes[path] = sha return path, sha, data def load(self, path): path, sha, data = self.pin(path) if path not in self.values: if sha not in self.by_digest: self.by_digest[sha] = json.loads(data) self.values[path] = self.by_digest[sha] return self.values[path] def verify(self): for path in tuple(self.hashes): self.pin(path) class ObservedReader: def __init__(self, reader, emit): self.reader = reader self.emit = emit self.verification_started = False def __getattr__(self, name): return getattr(self.reader, name) def consume(self, *args, **kwargs): if kwargs.get('verify_files', True) and not self.verification_started: self.verification_started = True self.emit('selected_attribute_verification_started') return self.reader.consume(*args, **kwargs) def verify_code(hashes): for path, sha in hashes.items(): if digest(path) != sha: raise ValueError('Preloaded implementation changed; restart service: ' + path) def reference_key(value): return json.dumps(value, sort_keys=True, separators=(',', ':'), allow_nan=False) def geometry_request(cache, original, runtime): request = dict(original) if runtime.get('prepared_support_surfaces'): prepared = cache.load(runtime['prepared_support_surfaces']) if prepared.get('schema') != 'rhg.prepared_support_surfaces.v1': raise ValueError('Unsupported prepared support surface index') refs = list(request.get('support_surface_feedback', [])) for ref in prepared['sources']: if ref not in refs: refs.append(ref) request['support_surface_feedback'] = refs if runtime.get('prepared_floor_body_geometry'): path = runtime['prepared_floor_body_geometry'] _, sha, _ = cache.pin(path) request.setdefault('floor_body_geometry_index', {'path': path, 'sha256': sha}) return request def warm(cases): started = time.monotonic() code = ROOT / 'source/scripts/internal/scene_generation/real_assets' sys.path[:0] = [str(code), str(code.parent), str(ROOT / 'source'), str(ROOT / 'inputs/native_site')] from style_attribute_consumer import load_attribute_releases import floor_body_geometry import layout_surface_feedback cache, readers, floors, surfaces = FrozenCache(), {}, {}, {} for case in cases: attempt = case / 'execution/chain/round_01/attempt_01' log = attempt / 'native_stage_00.log' cache.pin(log) bind = None for line in log.read_text().splitlines(): try: row = json.loads(line) except json.JSONDecodeError: continue if row.get('event') == 'stage_done' and row.get('name') == 'bind_prepared_0': bind = row break if bind is None: raise ValueError('Retained bind argv missing: ' + str(case)) argv = bind['argv'] scene = Path(argv[argv.index('--output-scene') + 1]) source = Path(argv[argv.index('--source-scene') + 1]) runtime = cache.load(attempt / 'runtime.json') for path in (source / 'composition_manifest.runtime.json', scene / '_candidate_snapshot.json', scene / 'eligible_scene_request.json', scene / 'shell_geometry_input.json', scene / 'selection_replay.json', scene / 'joint_search_report.json'): if case not in path.resolve().parents: raise ValueError('Retained input escapes case') cache.load(path) request = geometry_request(cache, cache.load(scene / 'eligible_scene_request.json'), runtime) reference = request.get('floor_body_geometry_index') key = reference_key(reference) if key not in floors: if reference: index = cache.load(reference['path']) for name in ('sources', 'support_obstacle_sources'): for item in index.get(name, []): cache.pin(item['path']) for name in ('probe_floor_body_geometry.py', 'probe_support_obstacles.py'): cache.pin(code / name) print(json.dumps({'event': 'loading_floor_evidence', 'case': str(case)}), flush=True) floors[key] = floor_body_geometry.load(reference) references = request.get('support_surface_feedback', []) key = reference_key(references) if key not in surfaces: for item in references: cache.pin(item['path']) surfaces[key] = layout_surface_feedback.load(request) path = str(Path(runtime['attribute_release']).resolve()) if path not in readers: print(json.dumps({'event': 'loading_attributes', 'path': path}), flush=True) spec = cache.load(path) reader = load_attribute_releases(path) readers[path] = reader for release in getattr(reader, 'releases', [reader]): cache.pin(release.path) cache.pin(release.path.parent / 'delivery.json') for item in spec.get('functional_patches', []): cache.pin(item['path']) helper_path = Path(__file__).with_name('replay_joint_layout.py') spec = importlib.util.spec_from_file_location('retained_replay', helper_path) helper = importlib.util.module_from_spec(spec) spec.loader.exec_module(helper) helper.preloaded_floors = floors helper.preloaded_surfaces = surfaces loaded = {str(Path(__file__).resolve()): digest(__file__), str(helper_path): digest(helper_path)} for module in tuple(sys.modules.values()): path = getattr(module, '__file__', None) if path and str(path).endswith('.py') and ROOT in Path(path).resolve().parents: loaded[str(Path(path).resolve())] = digest(path) if 'joint_layout' in sys.modules: raise ValueError('Preloader must not freeze native solver implementation') receipt = dict(schema='rhg.replay-preload.v1', cases=[str(p) for p in cases], input_sha256=dict(cache.hashes), loaded_code_sha256=dict(loaded), preload_elapsed_s=round(time.monotonic() - started, 3), constraints_modified=False, budget_modified=False, physical_qualified=False, whole_task_acceptance=False) return cache, readers, helper, loaded, receipt def run_child(connection, command, state, cases): cache, readers, helper, loaded, receipt = state output = Path(command['output']).resolve() result_returned = False try: case = Path(command['case']).resolve() if case not in cases: raise ValueError('Case was not preloaded') cache.verify() verify_code(loaded) import style_attribute_consumer original = style_attribute_consumer.load_attribute_releases started = time.monotonic() def emit(event, **values): print(json.dumps(dict(event=event, case=str(case), elapsed_since_replay_s=round(time.monotonic() - started, 3), **values)), flush=True) def reader(path): key = str(Path(path).resolve()) if key not in readers: raise ValueError('Attribute reader was not preloaded') return ObservedReader(readers[key], emit) style_attribute_consumer.load_attribute_releases = reader helper.load = cache.load import floor_body_geometry import layout_surface_feedback import joint_layout original_floor = floor_body_geometry.load original_surface = layout_surface_feedback.load original_positions = joint_layout.positions original_solve = joint_layout.solve seen_rooms = set() def floor_load(reference): return helper.preloaded_floors[reference_key(reference)] def surface_load(request): return helper.preloaded_surfaces[reference_key(request.get('support_surface_feedback', []))] def positions(entity, *args, **kwargs): room = entity['room_id'] if room not in seen_rooms: seen_rooms.add(room) emit('positions_room', room_id=room) return original_positions(entity, *args, **kwargs) def solve(*args, **kwargs): try: return original_solve(*args, **kwargs) except BaseException as error: tb = error.__traceback__ while tb is not None: if tb.tb_frame.f_code is original_solve.__code__: report = tb.tb_frame.f_locals.get('report') if report: helper.save(output / 'partial_joint_search_report.json', dict(report, passed=False, status='replay_did_not_complete', interrupted=isinstance(error, KeyboardInterrupt), all_room_searches_passed=bool(report['rooms']) and all(r.get('passed') for r in report['rooms']))) break tb = tb.tb_next raise floor_body_geometry.load = floor_load layout_surface_feedback.load = surface_load joint_layout.positions = positions joint_layout.solve = solve try: result = helper.replay(case, output) result_returned = True finally: style_attribute_consumer.load_attribute_releases = original floor_body_geometry.load = original_floor layout_surface_feedback.load = original_surface joint_layout.positions = original_positions joint_layout.solve = original_solve cache.verify() verify_code(loaded) helper.save(output / 'preload_receipt.json', receipt) reply = dict(result=result, preload_verified=True) except BaseException as error: reply = dict(passed=False, preload_verified=False, error=type(error).__name__ + ': ' + str(error), traceback=traceback.format_exc()) # A late cache failure invalidates the replay's own passing receipt too. result_path = output / 'result.json' if result_returned and result_path.is_file() and ROOT / 'runs' in output.parents: result = json.loads(result_path.read_text()) result.update(passed=False, preload_verified=False, preload_error=reply['error']) helper.save(result_path, result) connection.sendall((json.dumps(reply, allow_nan=False) + '\n').encode()) def serve(cases, directory): cases = tuple(p.resolve() for p in cases) directory = directory.resolve() if ROOT / 'runs' not in directory.parents: raise ValueError('Service directory must be new and under this version/runs') directory.mkdir(parents=True, exist_ok=False) state = warm(cases) (directory / 'preload_receipt.json').write_text(json.dumps(state[-1], indent=2) + '\n') socket_directory = Path(tempfile.mkdtemp(prefix='rhg-replay-')) address = socket_directory / 'control.sock' (directory / 'socket.json').write_text(json.dumps({'socket': str(address)}) + '\n') children = set() with socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) as server: server.bind(str(address)) os.chmod(address, 0o600) server.listen(8) server.settimeout(1) print(json.dumps({'event': 'ready', 'socket': str(address), 'preload_elapsed_s': state[-1]['preload_elapsed_s']}), flush=True) running = True while running or children: for pid in tuple(children): done, _ = os.waitpid(pid, os.WNOHANG) if done: children.remove(pid) if not running: time.sleep(.1) continue try: connection, _ = server.accept() except socket.timeout: continue try: connection.settimeout(15) command = json.loads(connection.makefile('rb').readline(65536)) if command.get('action') == 'stop': connection.sendall(b'{"stopping":true}\n') running = False elif command.get('action') == 'status': connection.sendall((json.dumps({'active_children': len(children), 'preload_elapsed_s': state[-1]['preload_elapsed_s']}) + '\n').encode()) elif command.get('action') == 'replay' and len(children) < 3: pid = os.fork() if pid == 0: server.close() try: run_child(connection, command, state, cases) finally: connection.close() os._exit(0) children.add(pid) else: connection.sendall(b'{"error":"Unknown action or three replays already active"}\n') except Exception as error: connection.sendall((json.dumps({'error': str(error)}) + '\n').encode()) finally: connection.close() address.unlink() socket_directory.rmdir() def main(): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument('--serve', action='store_true') parser.add_argument('--case', action='append', type=Path, default=[]) parser.add_argument('--directory', type=Path) parser.add_argument('--socket', type=Path) parser.add_argument('--output', type=Path) parser.add_argument('--action', choices=['replay', 'status', 'stop'], default='replay') args = parser.parse_args() if args.serve: if not args.case or args.directory is None: parser.error('--serve requires --case and --directory') serve(args.case, args.directory) return 0 if args.socket is None or (args.action == 'replay' and (len(args.case) != 1 or args.output is None)): parser.error('Client requires --socket; replay also requires one --case and --output') command = dict(action=args.action) if args.action == 'replay': command.update(case=str(args.case[0].resolve()), output=str(args.output.resolve())) with socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) as connection: connection.connect(str(args.socket)) connection.sendall((json.dumps(command) + '\n').encode()) reply = json.loads(connection.makefile('rb').readline()) print(json.dumps(reply, allow_nan=False), flush=True) return 1 if reply.get('error') or (args.action == 'replay' and not reply.get('result', {}).get('passed')) else 0 if __name__ == '__main__': raise SystemExit(main())