VEHwang's picture
Upload CoCogni4D-Bench (questions, media, scripts, render records, code) (part 4)
9d57416 verified
Raw History Blame Contribute Delete
8.43 kB
"""Read-only receipts for an NP trial; file presence never grants QA acceptance."""
from collections import deque
import json
from pathlib import Path
import re
from .errors import require
from .segment_import import MANIFEST, verify_import
from .review_layout import imports_root
FILE_LIMIT = 200_000
CHECK_KEY = re.compile(r'check|valid|stuck|bound|collision|conflict|arrange', re.I)
SELF_CHECK_SOURCE = {
'writer': 'embodied_pipeline/gen/run.py:280-282(check.referee;只在返回值里,没落盘)',
'runtime_only': 'embodied_pipeline/gen/run.py:280-282(check.referee;只在返回值里,没落盘)',
'scope': '当前源码定位;实际生成版本见 generator_commit。仅列 script.json/spec.json 已保存字段,字段存在不代表通过。',
}
def inside(root, relative):
root = Path(root).resolve()
require(isinstance(relative, str) and relative and not Path(relative).is_absolute(),
'RUN_FILE_PATH', '须提供试跑目录内的相对路径')
path = (root / relative).resolve()
require(path.is_relative_to(root) and path != root, 'RUN_FILE_PATH', '路径超出试跑目录')
return path
def read_file(run_dir, relative):
"""Return at most the first 200 KB, including for a permitted symlink."""
path = inside(run_dir, relative)
require(path.suffix.lower() in ('.json', '.jsonl', '.log', '.txt'),
'RUN_FILE_TYPE', '只允许 JSON、JSONL、LOG、TXT')
require(path.is_file(), 'RUN_FILE_NOT_FOUND', '证据文件不存在')
with path.open('rb') as stream:
return stream.read(FILE_LIMIT)
def _json(root, relative):
with inside(root, relative).open(encoding='utf-8') as stream:
return json.load(stream)
def _exists(root, relative):
return inside(root, relative).is_file()
def _tail(root, relative):
path = inside(root, relative)
if not path.is_file():
return ''
# Seek near the end; a pathological single-line log cannot consume the server.
with path.open('rb') as stream:
stream.seek(max(0, path.stat().st_size - FILE_LIMIT))
return '\n'.join(deque(stream.read(FILE_LIMIT).decode('utf-8', errors='replace').splitlines(), maxlen=20))
def _block(status='none', summary='', details=None, evidence=(), log_tail=''):
return dict(status=status, summary=summary, details=details, evidence=list(evidence), log_tail=log_tail)
def _fields(value, prefix=''):
found = {}
if isinstance(value, dict):
for key, child in value.items():
name = prefix + '.' + key if prefix else key
if CHECK_KEY.search(key):
found[name] = child
else:
found.update(_fields(child, name))
elif isinstance(value, list):
for index, child in enumerate(value):
found.update(_fields(child, f'{prefix}[{index}]'))
return found
def _selfcheck(root, sid):
fields, evidence = {}, []
for name in ('script.json', 'spec.json'):
relative = f'out/{sid}/{name}'
if _exists(root, relative):
evidence.append(relative)
fields.update({name + ':' + key: value for key, value in _fields(_json(root, relative)).items()})
return _block('warn' if fields else 'none', '自检相关字段已记录,未判定' if fields else '剧本内无自检字段',
dict(fields=fields, source=SELF_CHECK_SOURCE), evidence)
def _convert(root, imports, sid, log):
relative = f'{imports.relative_to(root)}/{sid}/{MANIFEST}'
evidence = [p for p in (relative, log) if _exists(root, p)]
if not _exists(root, relative):
return _block(summary='尚无转换产物', evidence=evidence, log_tail=_tail(root, log))
try:
manifest = verify_import(inside(root, f'{imports.relative_to(root)}/{sid}'))
return _block('ok', '导入指纹核验通过', manifest, evidence, _tail(root, log))
except (ValueError, KeyError, TypeError, AttributeError, OSError) as exc:
return _block('fail', '导入核验失败:' + str(exc), dict(error=str(exc)), evidence, _tail(root, log))
def _questions(root, sid):
summary_path, rows_path, log = f'vout/{sid}/summary.json', f'vout/{sid}/questions.jsonl', 'logs/questions.log'
evidence = [p for p in (summary_path, rows_path, log) if _exists(root, p)]
details = _json(root, summary_path) if _exists(root, summary_path) else None
if not _exists(root, rows_path):
return _block('fail' if details is not None else 'none', '出题结果缺失' if details is not None else '未出题', details, evidence, _tail(root, log))
counts, total = {}, 0
try:
with inside(root, rows_path).open(encoding='utf-8') as stream:
for line in stream:
if not line.strip():
continue
row = json.loads(line)
result = row['decision']['result']
counts[result] = counts.get(result, 0) + 1
total += 1
except (ValueError, KeyError, TypeError, OSError) as exc:
return _block('fail', '出题记录读取失败:' + str(exc), details, evidence, _tail(root, log))
mismatch = details is not None and details.get('candidates', total) != total
failed = bool((details or {}).get('execution_error')) or bool(counts.get('ERROR')) or mismatch
status = 'fail' if failed else 'ok' if counts.get('PASS') and details is not None else 'warn'
label = f'候选 {total},PASS {counts.get("PASS", 0)}(计划检查)'
if mismatch:
label += ';summary 候选分母不符'
if details is None:
label += ';缺 summary.json'
return _block(status, label, details, evidence, _tail(root, log))
def _render(root, sid):
artifact, error = f'r/{sid}/r/observation/artifact.json', f'render-errors/{sid}.txt'
evidence = [p for p in (artifact, error) if _exists(root, p)]
if _exists(root, error):
return _block('fail', '渲染失败记录', evidence=evidence, log_tail=_tail(root, error))
if _exists(root, artifact):
return _block('ok', '观测产物存在(未核验媒体)', evidence=evidence)
return _block(summary='未渲染')
def _guard(operation):
try:
return operation()
except (ValueError, KeyError, TypeError, AttributeError, OSError) as exc:
return _block('fail', '证据读取失败:' + str(exc), dict(error=str(exc)))
def build(run_dir):
root = Path(run_dir).resolve()
run = _json(root, 'run.json')
imports = imports_root(root, run)
segments = []
for row in run['segments']:
sid, index = row.get('script_id'), row['index']
log = f'logs/generate-{index}.log'
state = row.get('state')
# state may be failed by later stages. Preserve that overall fact separately.
generated = bool(sid and _exists(root, f'out/{sid}/script.json'))
generation_status = 'ok' if generated else 'fail' if state == 'failed' else 'warn' if state == 'generating' else 'none'
generation = _block(generation_status, '剧本已生成' if generated else str(state or '未生成'),
{k: row.get(k) for k in ('state', 'reason', 'seconds')},
[p for p in ('run.json', log) if _exists(root, p)], _tail(root, log))
blocks = dict(generation=generation,
selfcheck=_guard(lambda: _selfcheck(root, sid)) if sid else _block(summary='剧本内无自检字段'),
conversion=_guard(lambda: _convert(root, imports, sid, f'logs/convert-{index}.log')) if sid else _block(summary='尚无转换产物'),
questions=_guard(lambda: _questions(root, sid)) if sid else _block(summary='未出题'),
render=_guard(lambda: _render(root, sid)) if sid else _block(summary='未渲染'))
segments.append({**row, 'checks': blocks})
batch = _json(root, 'summary.json') if _exists(root, 'summary.json') else {}
return dict(schema='np-verify-report/1', run_id=run.get('id', root.name),
status=run.get('status'), root_alias=run.get('root_alias', run.get('id', root.name)),
generator_commit=run.get('generator_commit'), segments=segments,
errors=batch.get('errors'), generic_reasons=batch.get('generic_reasons'),
evidence=['run.json'] + (['summary.json'] if _exists(root, 'summary.json') else []))