"""Bounded generator → questions → review imports, with durable run records.""" import copy import datetime import fcntl import json from itertools import zip_longest import os from pathlib import Path import re import shlex import sys import tempfile import threading import time import uuid from np import final_select, planning from .batch_summary import summarize from .errors import ViewError, require from .np_gen_config import MAX_SEGMENTS, GenConfigBridge from .processes import encoded, execute, now, pin_checkout, stop from .review_layout import IMPORTS_DIR, LAYOUT_VERSION, RUN_SCHEMA, imports_root from .segment_import import MANIFEST REPO = Path(__file__).resolve().parents[3] def convert_command(segment, python, capability, out, vout): """一段剧本和 vout 转成剧本验收台目录(segment_conversion):控制台自己的步骤,不在 np 核心里。""" return [str(python), '-B', '-m', 'apps.console.server.segment_conversion', str(segment), str(capability), str(out), str(vout)] def arrangement_counts(view_path): """段卡的安排计数:数剧本验收台那一段的同一份安排清单(review.actual_arrangements),与段页口径一致;没有清单为 None。""" if not view_path.is_file(): return None events = (json.loads(view_path.read_text(encoding='utf-8')).get('review') or {}).get('actual_arrangements') if events is None: return None counts = dict(total=len(events), effective=0, deviated=0, ineffective=0) for event in events: if event['status'] in counts: counts[event['status']] += 1 return counts def write_json(path, data): temporary = path.with_suffix('.building') temporary.write_bytes(encoded(data) + b'\n') os.replace(temporary, path) def batch_result(root, run, generated): """summarize → batch_result.build → 补每段拒因和排布。""" summary = summarize(root / 'out', root / 'vout') summary_path = root / 'summary.json'; write_json(summary_path, summary) from apps.console.tools.batch_result import build result, _ = build(summary_path) rows = run['segments'] result.update(id=run['id'], scope=f"生成器 {run['generator_commit'][:7]} {len(rows)} 段;计划模型 PASS,不是渲染后验收") result['funnel'][0].update(label='本批生成的段', count=generated) reasons = {r['script_id']:{**r.get('prover_reasons', {}), **r['reasons']} for r in summary['per_case']} # 判前拒因也能筛段 outcome = {r['script_id']: r.get('arrangements') for r in rows if r.get('script_id')} for segment in result['segments']: segment['reasons'] = reasons[segment['script_id']] segment['arrangements'] = outcome.get(segment['script_id']) return result def planned_convert(): return shlex.join(convert_command('/out/', '', '/', f'/{IMPORTS_DIR}/', '/vout')) GEN_CHUNK = 16 # 一个 gen.run 进程至多几段:同一栋房子共用载入(c46b65fc,每段生成 CPU 13.2→5.0 s);块不大,屏 1 进度和单条时限仍按块走 def gen_chunks(rows): """按住宅分组(组内保持原序),每组切成至多 GEN_CHUNK 段一块,一块交一个 gen.run 进程。块之间仍串行(execute 只记一个子进程)。""" groups = {} for row in rows: groups.setdefault(row['config'].get('scene'), []).append(row) return [g[i:i + GEN_CHUNK] for g in groups.values() for i in range(0, len(g), GEN_CHUNK)] class NpRuns: def __init__(self, directory, generator_checkout, generator_commit, generator_python, capability_root, question_python, convert_python, publish, schema_settings, command_builders=None, timeouts=(600, 900, 120), *, on_rendered=None, render_cmd=None, expander=None, loader=None): self.directory = Path(directory).resolve() self.checkout = Path(generator_checkout).resolve() self.commit, self.python = generator_commit, str(generator_python) self.cap = Path(capability_root).resolve() self.question_python, self.convert_python = str(question_python), str(convert_python) self.publish, self.schema_settings = publish, dict(schema_settings or {}) self.builders = command_builders or (planning.generate_command, planning.question_command, convert_command) self.timeouts = timeouts # 批量设定只由生成器自己的 gen.expand 展开(经配置桥,在固定版本的生成器检出里跑),和屏1 第 3 卡看到的是同一份 bridge = GenConfigBridge(self.checkout, self.python, capability_root=self.cap) self.expand = expander or bridge.expand # 单段配置(屏 1 第 4 卡,可能手改过)只由生成器自己的 config.load 校验,和展开出来的段同一把尺子 self.load = loader or bridge.load self.on_rendered, self.render_cmd = on_rendered, render_cmd self.lock = threading.RLock() self.active = self.worker = self.child = self.owner = None self.closed = False for run in self.list_runs()['runs']: if run['status'] in ('completed', 'completed_with_failures'): self.publish(run['root_alias'], imports_root(self.directory / run['id'], run)) def worlds(self): """能力目录里实有的场景(有 capability.json 的子目录):屏1 的可选项、默认值和校验都只认这里。""" return sorted(p.parent.name for p in self.cap.glob('*/capability.json')) def _pin(self): if (self.checkout / '.git').exists(): return pin_checkout(self.checkout, self.commit) revision = self.checkout / 'REVISION' require(revision.is_file() and revision.read_text().strip() == self.commit, 'GENERATOR_COMMIT_MISMATCH', '生成器REVISION与固定版本不符') def _write(self, path, data): write_json(path, data) def _persist(self, run): with self.lock: self._write(self.directory / run['id'] / 'run.json', run) def start(self, config, limit, render=False, segment=None, repeat=False): """跑这批展开后的前 limit 段(试跑 1 段、整批都走这里);segment 给一段单次配置(屏 1 第 4 卡,可能手改过)时只跑这一段。""" with self.lock: require(not self.closed and self.active is None, 'GENERATION_BUSY', '已经有一批在运行') require(type(render) is bool, 'NP_CONFIG_INVALID', 'render须为true或false') # render is a run option, not batch config: keep it out of schema validation. if isinstance(config, dict) and 'render' in config: config = dict(config); value = config.pop('render') require(type(value) is bool, 'NP_CONFIG_INVALID', 'render须为true或false') render = render or value try: require(type(limit) is int and 1 <= limit <= MAX_SEGMENTS, 'NP_CONFIG_INVALID', '段数须为 1–%d' % MAX_SEGMENTS) require(segment is None or isinstance(segment, dict) and limit == 1, 'NP_CONFIG_INVALID', '只跑一段时 segment 须为单段配置、limit 须为 1') settings = dict(self.schema_settings) if settings.get('catalog') and settings.get('packages') and not settings.get('result'): settings['result'] = planning.CONTRACTS / 'batch-result.example.json' if settings.get('result') is not None and not isinstance(settings['result'], dict): settings['result'] = planning.read_json(settings['result']) planning.validate_schema(config, planning.batch_schema(**settings, worlds=self.worlds())) if settings.get('catalog') and settings.get('packages'): planning.plan(config, **settings, worlds=self.worlds()) if not any(config['targets'].values()): raise ValueError('至少一个母题目标') worlds = self.worlds() for scene, *_ in planning.batch_groups(config['batch']): if scene not in worlds: raise ValueError('场景能力目录不存在: ' + scene) except (ValueError, KeyError, TypeError, OSError) as exc: raise ViewError('NP_CONFIG_INVALID', str(exc)) from exc # segments follow from batch settings + seed (expand.py), so a second whole batch on both repeats the first one's # scripts and questions (9ff449c7 / 8d46c691, 10-23). A one-segment trial is exempt: the whole batch after it is # meant to reproduce the tried segment. repeat=True reruns on purpose. same = None if limit == 1 or segment is not None or repeat else self._same_batch(config['batch']) require(same is None, 'BATCH_REPEATS', '和批 %s 的设定、种子都相同,会生成同样的剧本;换个种子再开始' % same) self._pin() cases = self._trial(config['batch'], limit, segment) config = copy.deepcopy(config) config['render'] = render # The page may only switch rendering on; the command is a server start-up setting. if 'render_cmd' in config: raise ViewError('NP_CONFIG_INVALID', '渲染命令只能由服务启动参数设定') if config['render'] and not self.render_cmd: raise ViewError('NP_RENDER_NOT_CONFIGURED', '服务没有配置渲染命令(--np-render-cmd)') self.directory.mkdir(parents=True, exist_ok=True) if self.owner is None: handle = (self.directory / '.writer.lock').open('a+b') try: fcntl.flock(handle, fcntl.LOCK_EX | fcntl.LOCK_NB) except BlockingIOError: handle.close() raise ViewError('GENERATION_BUSY', '生成目录已有另一服务拥有') self.owner = handle id = datetime.datetime.now().strftime('np-%Y%m%dT%H%M%S-') + uuid.uuid4().hex[:8] root = self.directory / id (root / 'logs').mkdir(parents=True, exist_ok=False) (root / 'out').mkdir(); (root / IMPORTS_DIR).mkdir() self._write(root / 'config.json', config) run = dict(schema=RUN_SCHEMA, layout_version=LAYOUT_VERSION, review_imports=IMPORTS_DIR, id=id, status='running', created_at=now(), label=config['label'], limit=limit, generator_commit=self.commit, root_alias=id, stages=[dict(id=k, label=label, state='queued', done=0, total=len(cases), seconds=0) for k, label in [('generate','生成剧本'),('questions','出题和检查链'),('convert','转成审阅格式')]], segments=[{**c, 'script_id':None, 'state':'queued', 'reason':None, 'seconds':None, 'segment_id':None} for c in cases], result_url=None, error=None, commands=[]) if config['render']: run['stages'].append(dict(id='render', label='渲染视频', state='queued', done=0, total=len(cases), seconds=0)) self.active = run self._persist(run) self.worker = threading.Thread(target=self._run, args=(run,), daemon=True) self.worker.start() return copy.deepcopy(run) def _same_batch(self, batch): """Id of an earlier run of more than one segment on these exact batch settings and seed, else None.""" for path in sorted(self.directory.glob('np-*/config.json')): try: if planning.read_json(path).get('batch') == batch and planning.read_json(path.parent / 'run.json').get('limit', 1) > 1: return path.parent.name except (OSError, ValueError): continue return None def _trial(self, batch, limit, segment=None): """展开批量设定,按 planning.trial_order 轮流取各场景、各组的前 limit 份;segment 给了就只取它(经生成器校验)。生成器拒收的配置当场报出。""" if segment is not None: sid = segment.get('id') require(isinstance(sid, str) and re.fullmatch('[A-Za-z0-9_.+-]+', sid) and sid not in ('.', '..'), 'NP_CONFIG_INVALID', '单段配置的 id 不合法') require(segment.get('scene') in self.worlds(), 'NP_CONFIG_INVALID', '场景能力目录不存在: %s' % segment.get('scene')) picked = [self.load(segment)] else: configs = self.expand(batch)['configs'] try: picked = planning.trial_order(batch, configs)[:limit] except ValueError as exc: raise ViewError('NP_CONFIG_INVALID', str(exc)) from exc rows = [] for index, entry in enumerate(picked): cfg = entry['config'] if entry['errors']: raise ViewError('NP_CONFIG_INVALID', '生成器拒收配置 %s:%s' % (cfg.get('id'), entry['errors'][0])) # 场景按服务的能力目录解析成路径,gen.run 不再按它自己的默认能力根找 rows.append(dict(index=index, id=cfg['id'], world=cfg['scene'], seed=cfg['seed'], duration_s=cfg['duration_s'], arrangements=[dict(type=a['type'], strength=a.get('strength')) for a in cfg.get('arrangements', [])], config={**cfg, 'scene': str(self.cap / cfg['scene'])})) return rows @staticmethod def _needs(root, segments): """出题段每版要几题:config.json 的 targets.versions 按段数摊(向上取整,终选再按配额截),写 root/need.json。""" config = root / 'config.json' # 没有就是批次没设配额;有却坏了抛错,不当没有(重构稿 ⑧ H3) quotas = json.loads(config.read_text(encoding='utf-8')).get('targets', {}).get('versions', {}) if config.is_file() else {} path = root / 'need.json' write_json(path, {v: -(-int(q) // max(1, segments)) for v, q in quotas.items() if int(q) > 0}) return path def _command(self, run, argv, stage, name, cwd, extra_env, segments=1): env = dict(os.environ, PYTHONDONTWRITEBYTECODE='1', CUDA_VISIBLE_DEVICES='', OPENBLAS_NUM_THREADS='1', OMP_NUM_THREADS='1', MKL_NUM_THREADS='1', **extra_env) # 时限按段计:生成一条命令跑同一栋房子的几段(gen_chunks),时限乘段数 receipt = execute(self, argv, cwd, env, self.directory / run['id'] / 'logs' / (name + '.log'), self.timeouts[stage] * segments) run['commands'].append(receipt) self._persist(run) return receipt def _json_lines(self, run, name): """日志里按序的 JSON 对象行(gen.run 每份配置一行结论,gen/run.py main)。""" try: lines = (self.directory / run['id'] / 'logs' / (name + '.log')).read_text(errors='replace').splitlines() except OSError: return [] values = [] for line in lines: try: value = json.loads(line) except ValueError: continue if isinstance(value, dict): values.append(value) return values def _row_log(self, run, name, row, value): """核验页按段读 logs/generate-<序号>.log(verify_report):同一块一个进程,各段日志写出整组日志名、它那行结论和失败原因。""" text = '同一进程的整组日志:%s.log\n' % name + (json.dumps(value, ensure_ascii=False) + '\n' if value else '') (self.directory / run['id'] / 'logs' / ('generate-%d.log' % row['index'])).write_text(text + (row.get('reason') or '') + '\n') def _tail(self, run, name): # 失败原因带上日志最后一行(多是异常本身),屏 1 上不用翻日志就能看出为什么。 try: lines = [l.strip() for l in (self.directory / run['id'] / 'logs' / (name + '.log')).read_text(errors='replace').splitlines() if l.strip()] except OSError: return '' return ':' + lines[-1][:200] if lines else '' def _final_select(self, root, good): """Stage all outputs before replacing any; roll back a failed replacement.""" settings = self.schema_settings if not settings.get('catalog') or not settings.get('packages'): return dict(state='skipped', reason='没有目录,不做终选') changed = [] try: config = planning.read_json(root / 'config.json') quotas = config['targets']['versions'] families, _ = planning.catalog_data(settings['catalog'], settings['packages']) segments, grouped, pools = [], {}, {} for segment in good: if segment['state'] == 'failed': continue folder = root / 'vout' / segment['script_id'] path = folder / 'questions.jsonl' original = path.read_bytes() lines = [line for line in original.splitlines(keepends=True) if line.strip()] rows = [json.loads(line) for line in lines] try: script = planning.read_json(root / 'out' / segment['script_id'] / 'script.json') pool = ((script.get('generator') or {}).get('config') or {}).get('pool') except (OSError, ValueError): pool = None by_version = {} for row in rows: pools[id(row)] = pool by_version.setdefault(row['public']['version_id'], []).append(row) for vid, values in by_version.items(): grouped.setdefault(vid, []).append(values) segments.append((folder, original, lines, rows)) ordered = {vid: [row for turn in zip_longest(*groups) for row in turn if row is not None] for vid, groups in grouped.items()} chosen, report = final_select.select(ordered, quotas, families, seed=config.get('batch', {}).get('seed', 0), pool_of=lambda row: pools.get(id(row))) selected = {id(row) for values in chosen.values() for row in values} # Every temporary file lives on the same filesystem as its destination. with tempfile.TemporaryDirectory(prefix='.selection-', dir=root) as temporary: pending = [] def stage(path, content): staged = Path(temporary) / str(len(pending)) staged.write_bytes(content) pending.append((path, staged, path.read_bytes() if path.exists() else None)) for folder, original, lines, rows in segments: archive = folder / 'questions.all.jsonl' if archive.exists(): raise ValueError('终选原题备份已存在: ' + str(archive)) kept = [line for line, row in zip(lines, rows) if id(row) in selected] summary = planning.read_json(folder / 'summary.json') summary.update(candidates=len(kept), selection=dict(before=len(rows))) stage(archive, original) stage(folder / 'questions.jsonl', b''.join(kept)) stage(folder / 'summary.json', encoded(summary) + b'\n') stage(root / 'selection.json', encoded(report) + b'\n') for path, staged, original in pending: if path.name == 'questions.all.jsonl': source = path.with_name('questions.jsonl') os.replace(source, path) changed.append((source, path.read_bytes())) else: os.replace(staged, path) changed.append((path, original)) return dict(state='done', taken=sum(len(values) for values in chosen.values()), unfilled=report['unfilled'], received=sum(v['received'] for v in report['versions'].values())) except Exception as exc: for path, original in reversed(changed): if original is None: path.unlink() else: path.write_bytes(original) return dict(state='failed', reason=str(exc)) def _run(self, run): root = self.directory / run['id'] rows = run['segments'] try: stage = run['stages'][0]; stage['state'] = 'running'; self._persist(run) for chunk in gen_chunks(rows): begin = time.monotonic() paths = [] for row in chunk: row['state'] = 'generating' path = root / 'configs' / (row['id'] + '.json') path.parent.mkdir(exist_ok=True); self._write(path, row['config']); paths.append(path) self._persist(run) name = 'generate-batch-' + str(chunk[0]['index']) try: self._pin() receipt = self._command(run, self.builders[0](paths, self.python, root / 'out'), 0, name, self.checkout, {'PYTHONPATH':str(self.checkout)}, len(chunk)) # gen.run 每份配置按序一行结论:成功、被拒带 script_id,配置错带 config_error 和 config,别的错带 error 和 config lines, broken = [v for v in self._json_lines(run, name) if 'script_id' in v or 'config_error' in v or 'error' in v], None except Exception as exc: lines, broken = [], str(exc) for i, row in enumerate(chunk): value = lines[i] if i < len(lines) else None try: if broken: raise ValueError(broken) if value is None: raise ValueError('生成进程退出%d,这段没有结论行' % receipt['exit_code'] + self._tail(run, name)) if 'config_error' in value or 'error' in value: if value.get('config', str(paths[i])) != str(paths[i]): raise ValueError('生成器结论行和配置对不上:' + str(value.get('config'))) if 'config_error' in value: raise ValueError('生成器拒收这段的配置:' + value['config_error']) raise ValueError('生成器出错:' + value['error']) sid = value['script_id'] if not re.fullmatch('[A-Za-z0-9_.+-]+', sid) or sid in ('.', '..'): raise ValueError('生成剧本身份或文件不完整') if 'rejected' in value: code = value['rejected'] row['rejected'] = code # 结果屏按拒因分项计(stage rejected) raise ValueError('生成器排不出这段(%s):%s' % (code if code not in planning.GENERATOR_REJECT_LABELS else '%s,%s' % (planning.GENERATOR_REJECT_LABELS[code], code), json.dumps(value.get('detail', value), ensure_ascii=False)[:300])) folder = root / 'out' / sid if not (folder / 'curves.npz').is_file() or planning.read_json(folder / 'script.json')['script_id'] != sid: raise ValueError('生成剧本身份或文件不完整') row.update(script_id=sid, state='generated') except Exception as exc: row.update(state='failed', reason=str(exc)) self._row_log(run, name, row, value) row['seconds'] = (time.monotonic() - begin) / len(chunk) stage['done'] += 1; stage['seconds'] += row['seconds'] self._persist(run) stage['state'] = 'failed' if all(r['state'] == 'failed' for r in rows) else 'done' codes = [r['rejected'] for r in rows if r.get('rejected')] stage['rejected'] = [dict(code=c, label=planning.GENERATOR_REJECT_LABELS.get(c, c), count=codes.count(c)) for c in sorted(set(codes), key=codes.index)] good = [r for r in rows if r['state'] == 'generated'] stage = run['stages'][1]; stage.update(state='running', total=len(good)); self._persist(run) begin = time.monotonic() if good: receipt = self._command(run, self.builders[1]([root / 'out' / r['script_id'] for r in good], self.question_python, root / 'vout'), 1, 'questions', REPO, {'PYTHONPATH':str(REPO), 'NP_QUESTION_NEED':str(self._needs(root, len(good)))}) for row in good: try: summary = planning.read_json(root / 'vout' / row['script_id'] / 'summary.json') if summary['script_id'] != row['script_id'] or summary.get('execution_error') or receipt['exit_code'] == 124: raise ValueError('出题执行失败或超时') if not (root / 'vout' / row['script_id'] / 'questions.jsonl').is_file(): raise ValueError('出题结果缺失') stage['done'] += 1 except Exception as exc: row.update(state='failed', reason=str(exc)) stage.update(state='done' if stage['done'] == len(good) else 'failed', seconds=time.monotonic()-begin) self._persist(run) run['selection'] = self._final_select(root, good) if run['selection']['state'] == 'failed': raise ValueError('终选失败:' + run['selection']['reason']) stage = run['stages'][2]; stage.update(state='running', total=len(good)); self._persist(run) for row in good: begin = time.monotonic() sid = row['script_id'] if not (root / 'vout' / sid / 'summary.json').is_file(): continue try: receipt = self._command(run, self.builders[2](root / 'out' / sid, self.convert_python, self.cap / row['world'], imports_root(root, run) / sid, root / 'vout'), 2, 'convert-' + str(row['index']), REPO, {'PYTHONPATH':str(REPO)}) if receipt['exit_code'] or not (imports_root(root, run) / sid / MANIFEST).is_file(): raise ValueError('转换进程退出%d或缺少导入产物' % receipt['exit_code'] + self._tail(run, 'convert-' + str(row['index']))) row['segment_id'] = run['root_alias'] + '/' + sid row['arrangements'] = arrangement_counts(imports_root(root, run) / sid / 'view.json') if row['state'] != 'failed': row['state'] = 'converted' stage['done'] += 1 except Exception as exc: row.update(state='failed', reason=str(exc)) stage['seconds'] += time.monotonic()-begin; self._persist(run) stage['state'] = 'done' if stage['done'] == stage['total'] else 'failed' write_json(root / 'batch-result.json', batch_result(root, run, len(good))) self.publish(run['root_alias'], imports_root(root, run)) render_failed = False config = planning.read_json(root / 'config.json') if config.get('render', False): from apps.console.tools.render_run import render_run stage = run['stages'][3] stage.update(state='running', total=len(list((root / 'out').glob('*/')))) self._persist(run) def rendered(sid, outcome): for row in rows: if row['script_id'] == sid: row['render'] = dict(outcome) stage['done'] += 1 self._persist(run) begin = time.monotonic() counts, _ = render_run(root, render_cmd=self.render_cmd, on_segment=rendered, cancelled=lambda: self.closed) for row in rows: if 'render' not in row: row['render'] = dict(state='skipped', seconds=0., reason='没有已登记的生成段') stage.update(state='failed' if counts['failed'] else 'done', seconds=time.monotonic()-begin) render_failed = bool(counts['failed']) self._persist(run) if self.on_rendered is not None: try: # media index and review packs are views of the rendered files: their failure keeps the results self.on_rendered(run['id'], root) except Exception as exc: render_failed = True run['after_render_error'] = '%s: %s' % (type(exc).__name__, exc) print('渲染后整理失败', root, run['after_render_error'], file=sys.stderr) failed = sum(r['state'] == 'failed' for r in rows) if failed == len(rows): run.update(status='failed', error='%d段全部失败,见各段原因' % failed) else: run.update(status='completed_with_failures' if failed or render_failed else 'completed', result_url='/api/v1/np/result?run=' + run['id']) except Exception as exc: run.update(status='failed', error=str(exc)) for stage in run['stages']: if stage['state'] == 'running': stage['state'] = 'failed' finally: with self.lock: self._persist(run); self.active = None def list_runs(self): with self.lock: rows = [] for path in self.directory.glob('np-*/run.json'): row = planning.read_json(path) imports_root(path.parent, row) rows.append(row) for row in rows: if row['status'] == 'running' and (self.active is None or self.active['id'] != row['id']): row.update(status='failed', error='服务中断,结果未验证') return dict(schema='np-runs/1', runs=sorted(rows, key=lambda r:r['created_at'], reverse=True)) def get(self, id): for run in self.list_runs()['runs']: if run['id'] == id: return run raise ViewError('RUN_NOT_FOUND', '运行未登记') def result(self, id): run = self.get(id) require(run['status'] in ('completed','completed_with_failures'), 'RUN_RESULT_NOT_READY', '结果尚未完成') return planning.read_json(self.directory / id / 'batch-result.json') def close(self): with self.lock: self.closed = True; child = self.child if child: stop(child) if self.worker: self.worker.join(timeout=30) if self.owner: self.owner.close(); self.owner = None