File size: 16,019 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
"""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())