File size: 11,536 Bytes
5afd2f7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Bounded rendering of a generated run; native dependencies stay in the child."""
import argparse
from concurrent.futures import ThreadPoolExecutor
import fcntl
import json
import math
import os
import queue
from pathlib import Path
import shlex
import signal
import subprocess
import sys
import tempfile
import time

REPO = Path(__file__).resolve().parents[3]
DEFAULT_RENDER_CMD = (shlex.quote(sys.executable) + ' -B -m embodied_pipeline.runtime.render_cli render-script '
    '--script {segment_dir} --capability {capability} --assets {segment_dir}/assets.json '
    '--spec {segment_dir}/spec.json --out {out_dir}/r --max-wall-s {max_wall_s}')
# 渲染墙钟约为剧本时长的 4.7 倍(10-22 GPU 19032:90 s 剧本 425.7 s),时限取它的 2 倍再取整到 10 倍;
# 一律 900 s 时 360 s 剧本必超时。
RENDER_S_PER_SCRIPT_S = 10


def segment_timeout(segment, floor):
    span = json.loads((segment / 'script.json').read_text()).get('span_s')   # [起, 止] 世界秒(gen/export.py)
    return max(floor, math.ceil(RENDER_S_PER_SCRIPT_S * (float(span[1]) - float(span[0])))) if span else floor


def command_for(segment, out, template=None, max_wall_s=900):
    values = dict(segment_dir=str(segment), out_dir=str(out), max_wall_s=str(int(max_wall_s)))
    template = template or DEFAULT_RENDER_CMD
    if '{capability}' in template:
        script = json.loads((segment / 'script.json').read_text())
        values['capability'] = str(Path(script['generator']['house']) / 'capability.json')
    # Split before substitution: a path with spaces or shell syntax stays one argument.
    return [token.format(**values) for token in shlex.split(template)]


def _render(segment, out, argv, timeout, cancelled):
    begin = time.monotonic()
    reason = None
    try:
        if cancelled():
            raise RuntimeError('渲染已取消')
        if out.exists():
            raise RuntimeError('渲染输出已存在但缺少完成包;保留失败产物,请使用新运行目录')
        with tempfile.TemporaryFile() as stdout, tempfile.TemporaryFile() as stderr:
            child = subprocess.Popen(argv, cwd=REPO, stdout=stdout, stderr=stderr, start_new_session=True)
            try:
                deadline = begin + timeout
                while child.poll() is None:
                    if cancelled():
                        raise RuntimeError('渲染已取消')
                    remaining = deadline - time.monotonic()
                    if remaining <= 0:
                        raise TimeoutError('渲染超时(%s秒)' % timeout)
                    try:
                        child.wait(timeout=min(.1, remaining))
                    except subprocess.TimeoutExpired:
                        pass
            except BaseException:
                try:
                    os.killpg(child.pid, signal.SIGKILL)
                except ProcessLookupError:
                    pass
                child.wait()
                raise
            finally:
                stderr.seek(0, 2)
                stderr.seek(max(0, stderr.tell() - 8000))
                tail = stderr.read().decode('utf-8', errors='replace')[-2000:]
            if child.returncode:
                reason = tail or '渲染进程退出%d' % child.returncode
            elif not (out / 'r/observation/artifact.json').is_file():
                reason = '渲染进程退出0但缺少 r/observation/artifact.json'
    except Exception as exc:
        reason = str(exc)
        if 'tail' in locals() and tail:
            reason += '\n' + tail
    return dict(state='render_failed' if reason else 'rendered',
                seconds=time.monotonic() - begin, reason=reason)


def _native_jobs(plans):
    """Recognize the standard Habitat command; custom renderers stay per segment."""
    groups={};single=[]
    fields={'--script','--capability','--assets','--spec','--out','--max-wall-s'}
    for segment,out,argv,limit in plans:
        try:
            index=argv.index('render-script')
            if argv[index-1]!='embodied_pipeline.runtime.render_cli':raise ValueError()
            tail=argv[index+1:]
            if len(tail)%2:raise ValueError()
            flags=dict(zip(tail[::2],tail[1::2]))
            if set(flags)!=fields:raise ValueError()
            key=(tuple(argv[:index]),flags['--capability'])
            groups.setdefault(key,[]).append((segment,out,argv,limit,flags))
        except ValueError:single.append((segment,out,argv,limit))
    return groups,single


def _render_native_group(group,events,cancelled):
    begin=time.monotonic();remaining=list(group);child=None;reason=None
    try:
        with tempfile.TemporaryDirectory(prefix='native-render-') as tmp, tempfile.TemporaryFile() as stderr:
            jobs=[]
            for segment,out,argv,limit,flags in group:
                if out.exists():raise RuntimeError('渲染输出已存在但缺少完成包;请使用新运行目录')
                jobs.append({k[2:]:v for k,v in flags.items() if k!='--max-wall-s'})
            manifest=Path(tmp)/'jobs.json';manifest.write_text(json.dumps(jobs))
            prefix=group[0][2][:group[0][2].index('render-script')]
            argv=prefix+['render-batch','--backend','habitat','--jobs',str(manifest),
                         '--max-wall-s',str(max(x[3] for x in group))]
            if cancelled():raise RuntimeError('渲染已取消')
            child=subprocess.Popen(argv,cwd=REPO,stdout=subprocess.DEVNULL,stderr=stderr,start_new_session=True)
            job_started=begin
            while remaining:
                segment,out,_,limit,_=remaining[0]
                artifact=out/'r/observation/artifact.json';failure=out/'r/attempt-failure.json'
                if artifact.is_file() or failure.is_file():
                    error=None if artifact.is_file() else json.loads(failure.read_text()).get('reason','渲染失败')
                    events.put((segment,dict(state='rendered' if error is None else 'render_failed',
                        seconds=time.monotonic()-job_started,reason=error)))
                    remaining.pop(0);job_started=time.monotonic();continue
                if cancelled():raise RuntimeError('渲染已取消')
                if time.monotonic()-job_started>=limit:raise TimeoutError('渲染超时(%s秒)'%limit)
                if child.poll() is not None:
                    stderr.seek(0,2);stderr.seek(max(0,stderr.tell()-2000))
                    raise RuntimeError(stderr.read().decode('utf-8',errors='replace')[-2000:] or '渲染进程缺少完成包')
                time.sleep(.05)
            child.wait(timeout=10)
    except Exception as exc:reason=str(exc)
    finally:
        if child is not None and child.poll() is None:
            try:os.killpg(child.pid,signal.SIGKILL)
            except ProcessLookupError:pass
            child.wait()
        for segment,_,_,_,_ in remaining:
            events.put((segment,dict(state='render_failed',seconds=time.monotonic()-begin,reason=reason or '渲染进程失败')))


def render_run(run_dir, workers=2, timeout=900, render_cmd=None, dry_run=False,
               on_segment=None, cancelled=None):
    """Return counts and per-segment states; callbacks execute on the caller thread.

    An artifact's presence is a scheduling skip, not a claim of media validation.
    Dry runs print argv without creating any files or taking the writer lock.
    """
    root = Path(run_dir).resolve()
    if type(workers) is not int or workers < 1 or not math.isfinite(timeout) or timeout <= 0:
        raise ValueError('workers和timeout必须为正数,workers须为整数')
    if not (root / 'out').is_dir():
        raise ValueError('运行目录缺少 out/')
    segments = sorted(p for p in (root / 'out').iterdir() if p.is_dir())
    result = dict(rendered=0, failed=0, skipped=0, seconds={})
    states = {}

    def record(segment, row):
        states[segment.name] = row
        result['seconds'][segment.name] = row['seconds']
        key = dict(rendered='rendered', render_failed='failed', skipped='skipped')[row['state']]
        result[key] += 1
        if on_segment:
            on_segment(segment.name, row)

    def planned(segment):
        return command_for(segment, root / 'r' / segment.name, render_cmd, segment_timeout(segment, timeout))

    for segment in [s for s in segments if not (s / 'script.json').is_file()]:
        segments.remove(segment)
        record(segment, dict(state='skipped', seconds=0., reason='段目录里没有 script.json(生成没成),不渲染'))
    if dry_run:
        for segment in segments:
            if not (root / 'r' / segment.name / 'r/observation/artifact.json').is_file():
                print(shlex.join(planned(segment)))
        return result, states
    with (root / '.render.lock').open('a') as lock:
        fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB)
        errors = root / 'render-errors'
        errors.mkdir(exist_ok=True)
        with (root / 'render-commands.txt').open('a') as commands, ThreadPoolExecutor(max_workers=workers) as pool:
            pending = {};plans=[];events=queue.Queue()
            for segment in segments:
                out=root/'r'/segment.name
                if (out/'r/observation/artifact.json').is_file():
                    record(segment,dict(state='skipped',seconds=0.,reason='已有观测包;未重新核验媒体'));continue
                try:
                    argv=planned(segment);commands.write(shlex.join(argv)+'\n');commands.flush()
                    out.parent.mkdir(exist_ok=True)
                    plans.append((segment,out,argv,segment_timeout(segment,timeout)))
                except Exception as exc:record(segment,dict(state='render_failed',seconds=0.,reason=str(exc)))
            groups,single=_native_jobs(plans)
            for group in groups.values():pending[pool.submit(_render_native_group,group,events,cancelled or (lambda:False))]=None
            for segment,out,argv,limit in single:
                pending[pool.submit(_render,segment,out,argv,limit,cancelled or (lambda:False))]=segment
            while pending or not events.empty():
                try:segment,row=events.get(timeout=.05);record(segment,row)
                except queue.Empty:pass
                for future in list(pending):
                    if future.done():
                        segment=pending.pop(future)
                        result_row=future.result()
                        if segment is not None:record(segment,result_row)
        for name, row in states.items():
            if row['state'] == 'render_failed':
                path = errors / (name + '.txt')
                # Keep the first failure evidence on retries.
                if not path.exists():
                    path.write_text(row['reason'][-2000:] + '\n')
    return result, states


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument('--run', required=True, type=Path)
    parser.add_argument('--workers', type=int, default=2)
    parser.add_argument('--timeout', type=float, default=900)
    parser.add_argument('--render-cmd')
    parser.add_argument('--dry-run', action='store_true')
    args = parser.parse_args()
    result, _ = render_run(args.run, args.workers, args.timeout, args.render_cmd, args.dry_run)
    if not args.dry_run:
        print(json.dumps(result, ensure_ascii=False))
    return int(bool(result['failed']))


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