Datasets:
Download code/evaluation-code/ent400-a06a1576/np/run.py from VEHwang/cocogni4d: direct link, hf CLI and curl.
- Browser
- Download file 29.1 kB
-
https://huggingface.co/datasets/VEHwang/cocogni4d/resolve/main/code/evaluation-code/ent400-a06a1576/np/run.py
- Command line
-
hf download hf://datasets/VEHwang/cocogni4d/code/evaluation-code/ent400-a06a1576/np/run.py
-
curl -L -o run.py https://huggingface.co/datasets/VEHwang/cocogni4d/resolve/main/code/evaluation-code/ent400-a06a1576/np/run.py
29.1 kB
| """Resumable batch orchestration; domain work stays in the existing CLIs. | |
| main owns report/report.json for each invocation: status is partial when some | |
| segments fail but complete segments continue, failed on other stage errors, | |
| completed only when the scope reaches accept and all stages succeeded, | |
| otherwise partial (also while running). scope records effective from_stage, | |
| to_stage and only. stages maps every name to status and rc: executed/reused | |
| have rc=0, failed has the original rc, pending/not_selected have rc=None. | |
| outputs keeps gate/export/blind/receipts paths for this invocation's acceptance | |
| (including reuse); blind is the common sample/run/score directory. rc and | |
| failed_stage identify the invocation's failure, or 0 and None on success. | |
| segments and state/segments.json record the common complete/shortfall list. | |
| """ | |
| from collections import Counter, deque | |
| from concurrent.futures import ThreadPoolExecutor | |
| import hashlib | |
| import json | |
| import os | |
| from pathlib import Path | |
| from embodied_pipeline.domain import storage | |
| import signal | |
| import shlex | |
| import shutil | |
| import subprocess | |
| import sys | |
| import tempfile | |
| import time | |
| ROOT = Path(__file__).resolve().parents[1] | |
| SEGMENT_FILES = ('script.json', 'facts.npz', 'curves.npz') | |
| def read(path): | |
| return json.loads(Path(path).read_text(encoding='utf-8')) | |
| def write(path, value): | |
| path.parent.mkdir(parents=True, exist_ok=True) | |
| tmp = path.with_suffix('.tmp') | |
| tmp.write_text(json.dumps(value, ensure_ascii=False, indent=2) + '\n', encoding='utf-8') | |
| tmp.replace(path) | |
| def sha(value): | |
| return hashlib.sha256(json.dumps(value, sort_keys=True).encode()).hexdigest() | |
| def files(paths): | |
| result = {} | |
| for path in sorted(map(Path, paths)): | |
| if path.is_file(): | |
| digest = hashlib.sha256() | |
| with path.open('rb') as fh: | |
| for chunk in iter(lambda: fh.read(1024 * 1024), b''): | |
| digest.update(chunk) | |
| result[str(path)] = digest.hexdigest() | |
| return result | |
| class Failed(Exception): | |
| def __init__(self, rc, tail): | |
| self.rc, self.tail = rc, tail | |
| class Run: | |
| def __init__(self, args): | |
| self.root = Path(args.run).resolve() | |
| self.batch = read(args.batch) | |
| self.env = read(args.env) if args.env else {} | |
| shared_cache = Path(os.environ.get('XDG_CACHE_HOME') or Path.home()/'.cache')/'embodied-pipeline'/'gen-cache' | |
| self.env.setdefault('cache_root', os.environ.get('GEN_CACHE_ROOT') or str(shared_cache)) | |
| self.python = self.env.get('python', 'python3') | |
| self.jobs, self.only = args.jobs, args.only | |
| self.refill = getattr(args, 'refill_from', None) | |
| self.refill_round = getattr(args, 'refill_round', 1) | |
| if self.refill and (Path(self.refill).resolve() == self.root or not 0 < self.refill_round < 2**32): | |
| raise ValueError('refill requires a fresh RUN and a positive round') | |
| self.segments = None | |
| self.processes = set() | |
| if self.jobs < 1: | |
| raise ValueError('--jobs must be positive') | |
| self.code = subprocess.check_output(['git', 'rev-parse', 'HEAD'], cwd=ROOT, text=True).strip() | |
| self.process_env = dict(os.environ) | |
| mapping = dict(cap_root='GEN_CAP_ROOT', asset_root='EST_ASSET_ROOT', cache_root='GEN_CACHE_ROOT', | |
| threads='OMP_NUM_THREADS') | |
| for key, target in mapping.items(): | |
| if key in self.env: | |
| self.process_env[target] = str(self.env[key]) | |
| if 'threads' in self.env: | |
| self.process_env['OPENBLAS_NUM_THREADS'] = str(self.env['threads']) | |
| for key in ('GEN_CAP_ROOT', 'EST_ASSET_ROOT', 'GEN_OBJECTS_ROOT', 'OMP_NUM_THREADS', 'OPENBLAS_NUM_THREADS'): | |
| if key in self.env: | |
| self.process_env[key] = str(self.env[key]) | |
| for name in ('cfg', 'segs', 'logs', 'state/seg', 'vout', 'table', 'report'): | |
| (self.root / name).mkdir(parents=True, exist_ok=True) | |
| def module(self, name, *args): | |
| return [self.python, '-B', '-m', name, *map(str, args)] | |
| def cache(self): | |
| return ['--cache', str(self.env['cache_root'])] if self.env.get('cache_root') else [] | |
| def configs(self): | |
| return [p for p in sorted((self.root / 'cfg').glob('*.json')) if not self.only or self.only in p.stem] | |
| def complete_configs(self, *, allow_empty=False): | |
| """Freeze one eligibility list for every downstream consumer.""" | |
| if self.segments is None: | |
| complete, shortfall = [], {} | |
| for cfg in self.configs(): | |
| state = self.root / 'state/seg' / cfg.name | |
| result = read(state) if state.exists() else {} | |
| missing = [name for name in SEGMENT_FILES | |
| if not (self.root / 'segs' / cfg.stem / name).is_file()] | |
| if result.get('rc') == 0 and not missing: | |
| complete.append(cfg.stem) | |
| else: | |
| shortfall[cfg.stem] = dict(rc=result.get('rc'), missing=missing, | |
| stderr_tail=result.get('stderr_tail', '')) | |
| self.segments = dict(complete=complete, shortfall=shortfall) | |
| write(self.root / 'state/segments.json', self.segments) | |
| if not self.segments['complete'] and not allow_empty: | |
| raise ValueError('no complete segments selected') | |
| return [self.root / 'cfg' / (name + '.json') for name in self.segments['complete']] | |
| def caps(self): | |
| b = self.batch['batch'] | |
| scenes = b['grid']['scenes'] if 'grid' in b else [b['scene']] if 'scene' in b else [s['scene'] for s in b['scenes']] | |
| return [Path(self.process_env.get('GEN_CAP_ROOT', '')) / s for s in scenes] | |
| def terminate(self, proc=None): | |
| for child in (proc,) if proc is not None else tuple(self.processes): | |
| try: | |
| os.killpg(child.pid, signal.SIGKILL) | |
| except ProcessLookupError: | |
| pass | |
| if proc is not None: | |
| child.wait() | |
| def execute(self, argv, log, timeout=None): | |
| start, rc = time.monotonic(), 0 | |
| with log.open('ab') as out, tempfile.TemporaryFile() as err: | |
| try: | |
| proc = subprocess.Popen(list(map(str, argv)), cwd=ROOT, env=self.process_env, | |
| stdin=subprocess.DEVNULL, stdout=out, stderr=err, start_new_session=True) | |
| self.processes.add(proc) | |
| try: | |
| rc = proc.wait(timeout=timeout) | |
| except subprocess.TimeoutExpired: | |
| rc = 124 | |
| err.write(f'command timed out after {timeout}s\n'.encode()) | |
| finally: | |
| self.terminate(proc) | |
| self.processes.discard(proc) | |
| except OSError as exc: | |
| rc = 2 | |
| err.write((str(exc) + '\n').encode()) | |
| err.seek(0) | |
| tail = deque(maxlen=40) | |
| for line in err: | |
| out.write(line) | |
| tail.append(line.decode('utf-8', errors='replace')) | |
| result = dict(rc=rc, wall_s=time.monotonic()-start, stderr_tail=''.join(tail)) | |
| if rc: | |
| raise Failed(rc, result) | |
| return result | |
| def resolve(c): | |
| write(c.root / 'batch.json', c.batch['batch']) | |
| write(c.root / 'manifest.json', dict(run=str(c.root), code=c.code, env=c.env, batch_sha=sha(c.batch))) | |
| return [] | |
| def capability(c): | |
| worlds = c.env.get('world_artifacts', {}) | |
| commands = [c.module('embodied_pipeline.backends.scene_capability', 'bake', worlds[p.name], p) | |
| for p in c.caps() if p.name in worlds] | |
| write(c.root / 'state/capability-bake.json', dict(bake_commands=commands, | |
| missing_world_artifacts=[p.name for p in c.caps() if not p.exists() and p.name not in worlds])) | |
| for cap in c.caps(): | |
| yield c.module('embodied_pipeline.backends.scene_capability', 'validate', cap) | |
| def warm(c): | |
| yield c.module('embodied_pipeline.gen.run', '--warm', *c.caps(), *c.cache()) | |
| def expand(c): | |
| if c.refill: | |
| source = Path(c.refill).resolve() | |
| if list((c.root / 'cfg').glob('*.json')): | |
| raise ValueError('refill destination cfg must be empty') | |
| configs = sorted((source / 'cfg').glob('*.json')) | |
| if not configs or any(not (source / 'state/seg' / p.name).is_file() for p in configs): | |
| raise ValueError('refill source must have a result for every configuration') | |
| seeds = {} | |
| for cfg in configs: | |
| if c.only and c.only not in cfg.stem: | |
| continue | |
| if read(source / 'state/seg' / cfg.name).get('rc') == 0 and all( | |
| (source / 'segs' / cfg.stem / name).is_file() for name in SEGMENT_FILES): | |
| continue | |
| value = read(cfg) | |
| old = value['seed'] | |
| value['seed'] = (old + c.refill_round) % (2**32) | |
| seeds[cfg.stem] = dict(before=old, after=value['seed']) | |
| write(c.root / 'cfg' / cfg.name, value) | |
| if not seeds: | |
| raise ValueError('no failed positions selected') | |
| write(c.root / 'refill.json', dict(source=str(source), round=c.refill_round, seeds=seeds)) | |
| write(c.root / 'unfilled.json', {}) | |
| return | |
| # The CLI owns expansion, including capacity truncation and grid ordering. | |
| with tempfile.TemporaryDirectory(dir=c.root) as tmp: | |
| yield c.module('embodied_pipeline.gen.expand', c.root / 'batch.json', '--out', tmp, '--dry', *c.cache()) | |
| for old in (c.root / 'cfg').glob('*.json'): | |
| old.rename(Path(tmp) / ('old-' + old.name)) | |
| unfilled = {} | |
| for cfg in sorted((Path(tmp) / 'configs').glob('*.json')): | |
| value = read(cfg) | |
| unfilled[cfg.stem] = value.get('unfilled', []) | |
| cfg.replace(c.root / 'cfg' / cfg.name) | |
| write(c.root / 'unfilled.json', unfilled) | |
| if (Path(tmp) / 'structural-selection.json').exists(): | |
| write(c.root / 'structural-selection.json', read(Path(tmp) / 'structural-selection.json')) | |
| def generate(c): | |
| configs = c.configs() | |
| if not configs: | |
| raise ValueError('no configurations selected') | |
| def one(cfg): | |
| state = c.root / 'state/seg' / cfg.name | |
| key = sha(dict(config=files([cfg]), code=c.code, env=c.env, upstream=c.upstream.get("inputs_sha"))) | |
| old = read(state) if state.exists() else {} | |
| dest = c.root / 'segs' / cfg.stem | |
| if old.get('rc') == 0 and old.get('inputs_sha') == key and all( | |
| (dest / name).is_file() for name in SEGMENT_FILES): | |
| return 0 | |
| archived = [] | |
| if dest.exists(): | |
| archive = c.root / 'logs' / f'{cfg.stem}.failed-{time.time_ns()}' | |
| dest.rename(archive) | |
| archived.append(str(archive)) | |
| try: | |
| result = c.execute(c.module('embodied_pipeline.gen.run', '--config', cfg, '--out', c.root / 'segs', *c.cache()), | |
| c.root / 'logs' / (cfg.stem + '.log'), max(120, 4/3*read(cfg).get('duration_s', 90))) | |
| except Failed as exc: | |
| result = exc.tail | |
| write(state, dict(result, inputs_sha=key, config_sha=next(iter(files([cfg]).values())), | |
| archived=old.get('archived', []) + archived)) | |
| return result['rc'] | |
| with ThreadPoolExecutor(max_workers=c.jobs) as pool: | |
| codes = list(pool.map(one, configs)) | |
| with (c.root / 'logs/generate.log').open('ab') as log: | |
| for cfg in configs: | |
| path = c.root / 'logs' / (cfg.stem + '.log') | |
| if path.exists(): | |
| with path.open('rb') as source: | |
| for line in source: | |
| log.write(line) | |
| c.segments = None | |
| c.complete_configs() | |
| if any(codes): | |
| bad = next(read(c.root / 'state/seg' / p.name) for p in configs if read(c.root / 'state/seg' / p.name)['rc']) | |
| raise Failed(bad['rc'], bad) | |
| if c.segments['shortfall']: | |
| raise Failed(2, dict(rc=2, stderr_tail='generation outputs incomplete\n')) | |
| return [] | |
| def questions(c): | |
| configs = c.complete_configs() | |
| if any((c.root / 'vout').iterdir()): | |
| (c.root / 'vout').rename(c.root / 'logs' / f'vout-{time.time_ns()}') | |
| yield c.module('np.prover_questions', '--segments', *[c.root / 'segs' / p.stem for p in configs], '--out', c.root / 'vout') | |
| def tally(c): | |
| if any((c.root / 'table').iterdir()): | |
| (c.root / 'table').rename(c.root / 'logs' / f'table-{time.time_ns()}') | |
| (c.root / 'table').mkdir() | |
| (c.root / 'base').write_text(c.code + '\n') | |
| configs = c.complete_configs(allow_empty=True) | |
| for cfg in configs: | |
| source = c.root / 'vout' / cfg.stem | |
| summary = read(source / 'summary.json') | |
| counts, grouped, groups = Counter(), Counter(), set() | |
| for name, counter in [('questions.jsonl', counts), ('groups.jsonl', grouped)]: | |
| path = storage.stored_path(source / name) | |
| if name == 'groups.jsonl' and not path.exists(): | |
| continue # Explicit --versions without --groups writes only regular questions. | |
| with storage.open_read(path) as rows: | |
| for line in rows: | |
| if not line.strip(): | |
| continue | |
| row = json.loads(line) | |
| counter[row['public']['version_id']] += 1 | |
| if name == 'groups.jsonl': | |
| group = row['scope']['group'] | |
| groups.add((group['unit'], group['id'])) | |
| write(c.root / 'table' / (cfg.stem + '.counts.json'), dict( | |
| rc=0, house=Path(read(cfg)['scene']).name, q=counts + grouped, | |
| questions=dict(count=sum(counts.values()), q=counts), | |
| # A paired package is identified by (unit, id), as in group_stats.packs. | |
| groups=dict(count=len(groups), questions=sum(grouped.values()), q=grouped))) | |
| write(c.root / 'table' / (cfg.stem + '.summary.json'), summary) | |
| yield c.module('embodied_pipeline.prover.wp_table', c.root / 'table', '--code', ROOT, | |
| '--json', c.root / 'table/table.json', '--md', c.root / 'table/table.md', | |
| *(['--allow-empty'] if not configs else [])) | |
| def accept(c): | |
| from . import final_select | |
| configs = c.complete_configs() | |
| out = Path(tempfile.mkdtemp(prefix='accept-', dir=c.root / 'report')) | |
| paths = {name: str(out / name) for name in ('gate', 'export', 'blind', 'receipts')} | |
| c.accept_outputs = paths | |
| expected = out / 'expected' | |
| expected.mkdir() | |
| questions = out / 'questions' | |
| questions.mkdir() | |
| grouped, offsets = {}, {} | |
| for cfg in configs: | |
| (expected / cfg.name).write_bytes(cfg.read_bytes()) | |
| grouped[cfg.stem], offsets[cfg.stem] = [], {} | |
| # Keep only selector inputs in memory; proofs are reread for selected rows. | |
| with storage.open_read(c.root / 'vout' / cfg.stem / 'groups.jsonl', 'rb') as source: | |
| for offset, line in enumerate(source): | |
| if not line.strip(): | |
| continue | |
| row = json.loads(line) | |
| compact = {k: row[k] for k in ('scope', 'public', 'replay', 'decision') if k in row} | |
| grouped[cfg.stem].append(compact) | |
| offsets[cfg.stem][id(compact)] = offset | |
| del row | |
| declared = read(ROOT / 'embodied_pipeline/prover/groups.json')['units'] | |
| versions = {kind['version'] for unit in declared for kind in unit['kinds'].values() if kind.get('version')} | |
| chosen, selection = final_select.select_groups(grouped, seed=c.batch['batch'].get('seed', 0), versions=versions) | |
| write(out / 'selection.json', selection) | |
| for sid, values in chosen.items(): | |
| source_dir = c.root / 'vout' / sid | |
| # Copy auxiliary assets, but never copy the unselected proof corpus. | |
| shutil.copytree(source_dir, questions / sid, | |
| ignore=lambda directory, names: {'groups.jsonl', 'groups.jsonl.zst'} if Path(directory) == source_dir else set()) | |
| destination = questions / sid / 'groups.jsonl' | |
| # Spool only selected lines, then replay the selector's exact output order. | |
| wanted = {offsets[sid][id(row)] for row in values} | |
| positions = {} | |
| with tempfile.TemporaryFile() as spool, storage.open_read(source_dir / 'groups.jsonl', 'rb') as source: | |
| for number, line in enumerate(source): | |
| if number in wanted: | |
| positions[number] = spool.tell() | |
| spool.write(line if line.endswith(b'\n') else line + b'\n') | |
| with storage.open_write(destination, 'wb') as dest: | |
| for row in values: | |
| spool.seek(positions[offsets[sid][id(row)]]) | |
| dest.write(spool.readline()) | |
| # External gates may predate compressed intermediates; never rewrite them. | |
| with storage.plain_view(questions) as gate_questions, storage.plain_view(c.env['front']) as gate_front: | |
| yield [c.python, '-B', c.env['pkg_gate'], '--new', gate_questions, '--front', gate_front, | |
| '--contract', c.env['contract'], '--expect', expected, '--out', paths['gate']] | |
| yield c.module('tools.evaluation.np_export', '--questions', *[questions / p.stem / 'groups.jsonl' for p in configs], | |
| '--scripts', c.root / 'segs', '--out', paths['export']) | |
| yield [c.python, '-B', str(ROOT / 'tools/evaluation/blind_codex.py'), 'sample', paths['export'], paths['blind']] | |
| # receipts checks every exported item; score its explicitly recorded sample. | |
| n = sum(bool(s.strip()) for s in (Path(paths['blind']) / 'items.jsonl').read_text().splitlines()) | |
| write(Path(paths['blind']) / 'export.json', dict(source=paths['export'], | |
| denominator=dict(pass_rows=n, items=n, skipped_pass=0))) | |
| for action, args in [('run', [paths['blind']]), ('score', [paths['blind']])]: | |
| yield [c.python, '-B', str(ROOT / 'tools/evaluation/blind_codex.py'), action, *args] | |
| yield [c.python, '-B', str(ROOT / 'tools/evaluation/receipts.py'), '--export', paths['blind'], | |
| '--run', paths['blind'], '--out', paths['receipts']] | |
| def identity(c): | |
| result = dict(batch=c.batch, code=c.code, env=c.env) | |
| if c.refill: | |
| source = Path(c.refill).resolve() | |
| result['refill'] = dict(source=str(source), round=c.refill_round, | |
| inputs=files([*(source / 'cfg').glob('*.json'), | |
| *(source / 'state/seg').glob('*.json')])) | |
| return result | |
| def selected(c): | |
| return dict(only=c.only, configs=files(c.configs())) | |
| def complete(c): | |
| # Fingerprinting records empty eligibility; executing questions/accept still rejects it. | |
| configs = c.complete_configs(allow_empty=True) | |
| return dict(selected(c), segments=c.segments, artifacts=files( | |
| c.root / 'segs' / cfg.stem / name for cfg in configs | |
| for name in SEGMENT_FILES)) | |
| def capabilities(c): | |
| return files(p for cap in c.caps() for p in cap.rglob('*') if p.is_file()) | |
| def acceptance(c): | |
| return dict(complete(c), external=files([c.env[k] for k in ('pkg_gate', 'contract') if k in c.env]), | |
| front=files(storage.stored_glob(Path(c.env.get('front', '')), '*/groups.jsonl'))) | |
| def outputs(*patterns): | |
| return lambda c: [p for pattern in patterns for p in c.root.glob(pattern) if p.is_file()] | |
| STAGES = [ | |
| ('resolve', identity, resolve, outputs('manifest.json', 'batch.json')), | |
| ('capability', capabilities, capability, outputs('state/capability-bake.json')), | |
| ('warm', identity, warm, outputs()), | |
| ('expand', identity, expand, outputs('cfg/*.json', 'unfilled.json')), | |
| ('generate', selected, generate, outputs('segs/**/*', 'state/seg/*.json')), | |
| ('questions', complete, questions, outputs('vout/**/*')), | |
| ('tally', complete, tally, outputs('table/*')), | |
| ('accept', acceptance, accept, outputs('report/accept-*/**/*')), | |
| ] | |
| def trial_scope(c): | |
| """Count houses before starting work; --only uses canonical config ids.""" | |
| b = c.batch['batch'] | |
| if c.only and b and 'scene' not in b: | |
| from embodied_pipeline.gen.expand import expand | |
| configs = [cfg for cfg in expand(b) if c.only in cfg['id']] | |
| if not configs: | |
| raise ValueError('no configurations selected') | |
| return dict(houses=sorted({cfg['scene'] for cfg in configs}), segments=len(configs)) | |
| if 'grid' in b: | |
| g = b['grid'] | |
| houses = g['scenes'] | |
| n = len(houses) * len(g['humans']) * len(g['seeds']) | |
| elif 'scene' in b: | |
| houses, n = [b['scene']], sum(g.get('count', 1) for g in b.get('groups', [])) | |
| elif 'scenes' in b: | |
| houses = [s['scene'] for s in b['scenes']] | |
| n = sum(s.get('count', g.get('count', 1)) for s in b['scenes'] | |
| for g in b.get('template', {}).get('groups', [{}])) | |
| else: | |
| configs = [read(p) for p in c.configs()] | |
| houses, n = [cfg.get('scene', '') for cfg in configs], len(configs) | |
| return dict(houses=sorted(set(houses)), segments=n) | |
| def check_trial(c, args, scope): | |
| reason = getattr(args, 'no_trial_check', None) | |
| if reason is not None: | |
| if not reason.strip(): | |
| raise ValueError('--no-trial-check requires a nonempty reason') | |
| return dict(status='bypassed', reason=reason) | |
| if len(scope['houses']) < 2: | |
| return dict(status='single_house') | |
| source = Path(getattr(args, 'trial_run', None) or c.root).resolve() / 'state/trial.json' | |
| try: | |
| trial = read(source) | |
| valid = (trial['schema'] == 'np-trial/1' and trial['code'] == c.code and len(trial['houses']) == 1 | |
| and trial['questions_rc'] == 0 | |
| and trial['questions'] >= 1 and 0 < trial['complete'] <= trial['segments']) | |
| except (OSError, ValueError, KeyError, TypeError): | |
| valid = False | |
| if not valid: | |
| command = [c.python, '-B', '-m', 'np', 'run', str(args.batch), '--run', str(c.root) + '-trial', | |
| '--only', 'H00' if 'grid' in c.batch['batch'] else Path(scope['houses'][0]).name] | |
| if args.env: | |
| command += ['--env', str(args.env)] | |
| raise ValueError('no successful same-code single-house trial; first run: ' + shlex.join(command) | |
| + '\nthen rerun this batch with --trial-run ' + shlex.quote(str(c.root) + '-trial')) | |
| rate = trial['complete'] / trial['segments'] | |
| print(f"trial {source}: 成段率 {trial['complete']}/{trial['segments']} = {rate:.1%}; " | |
| f"本批预计成段数 {scope['segments'] * rate:.2f}/{scope['segments']}") | |
| return dict(status='passed', source=str(source), record=trial, | |
| expected_segments=scope['segments'] * rate) | |
| def record_trial(c, report, scope): | |
| """F148 qualifies successful questions; acceptance remains a recorded result.""" | |
| if len(scope['houses']) != 1 or report['stages'].get('questions', {}).get('rc') != 0: | |
| return | |
| configs = c.configs() | |
| complete = (c.segments or {}).get('complete', []) | |
| if not 0 < len(complete) <= len(configs): | |
| return | |
| count = sum(sum(bool(line.strip()) for line in storage.iter_lines(path)) | |
| for name in complete for filename in ('questions.jsonl', 'groups.jsonl') | |
| if (path := storage.stored_path(c.root / 'vout' / name / filename)).is_file()) | |
| if count: | |
| write(c.root / 'state/trial.json', dict(schema='np-trial/1', code=c.code, houses=scope['houses'], | |
| segments=len(configs), complete=len(complete), questions=count, | |
| questions_rc=0, accept_rc=report['stages'].get('accept', {}).get('rc'))) | |
| def main(args): | |
| c = Run(args) | |
| def stop(number, frame): | |
| c.terminate() | |
| raise SystemExit(128 + number) | |
| handlers = {s: signal.signal(s, stop) for s in (signal.SIGTERM, signal.SIGINT)} | |
| try: | |
| return _main(c, args) | |
| finally: | |
| c.terminate() | |
| for number, handler in handlers.items(): | |
| signal.signal(number, handler) | |
| def _main(c, args): | |
| names = [s[0] for s in STAGES] | |
| lo, hi = names.index(args.from_stage or names[0]), names.index(args.to_stage or names[-1]) | |
| if lo > hi: | |
| raise ValueError('--from must precede --to') | |
| c.accept_outputs = {} | |
| report = dict(outputs={}, status='partial', rc=0, failed_stage=None, code=c.code, | |
| scope=dict(from_stage=names[lo], to_stage=names[hi], only=c.only), | |
| stages={name: dict(status='pending' if lo <= i <= hi else 'not_selected', rc=None) | |
| for i, name in enumerate(names)}) | |
| report_path = c.root / 'report/report.json' | |
| try: | |
| scope = trial_scope(c) | |
| report['trial_check'] = check_trial(c, args, scope) | |
| except (OSError, ValueError, KeyError, TypeError) as exc: | |
| report.update(status='failed', rc=2, failed_stage='trial_check', | |
| trial_check=dict(status='failed', error=str(exc))) | |
| write(report_path, report) | |
| print(str(exc), file=sys.stderr) | |
| return 2 | |
| write(report_path, report) | |
| dirty, upstream = False, {} | |
| for index, (name, inputs, command, products) in enumerate(STAGES): | |
| if index > hi: | |
| break | |
| state = c.root / 'state' / (name + '.json') | |
| old = read(state) if state.exists() else {} | |
| c.upstream = upstream | |
| try: | |
| key = sha(dict(inputs=inputs(c), upstream=upstream, code=c.code, env=c.env)) | |
| except (OSError, ValueError, KeyError, TypeError) as exc: | |
| if c.segments is not None: | |
| report['segments'] = c.segments | |
| report['stages'][name] = dict(status='failed', rc=2) | |
| report.update(status='failed', rc=2, failed_stage=name) | |
| write(report_path, report) | |
| record_trial(c, report, scope) | |
| print(str(exc), file=sys.stderr) | |
| return 2 | |
| executed = False | |
| missing_outputs = name == 'generate' and any( | |
| not (c.root / 'segs' / cfg.stem / filename).is_file() | |
| for cfg in c.configs() for filename in SEGMENT_FILES) | |
| if lo <= index <= hi and (dirty or missing_outputs or old.get('rc') != 0 or old.get('inputs_sha') != key): | |
| executed = True | |
| dirty, start = True, time.monotonic() | |
| result = dict(rc=0, stderr_tail='') | |
| log = c.root / 'logs' / (name + '.log') | |
| log.write_text('') | |
| try: | |
| for argv in command(c): | |
| limit = c.env.get('questions_timeout_s', 60*len(c.complete_configs())) if name == 'questions' else None | |
| if name == 'questions': | |
| argv += ['--deadline', str(max(0, limit - min(30, limit / 10)))] | |
| c.execute(argv, log, timeout=limit) | |
| except Failed as exc: | |
| result = exc.tail | |
| except (OSError, ValueError, KeyError, TypeError) as exc: | |
| result = dict(rc=2, stderr_tail=str(exc)) | |
| with log.open('a') as fh: | |
| fh.write(str(exc) + '\n') | |
| old = dict(result, inputs_sha=key, outputs=list(map(str, products(c))), wall_s=time.monotonic()-start) | |
| if name == 'capability' and (c.root / 'state/capability-bake.json').exists(): | |
| old.update(read(c.root / 'state/capability-bake.json')) | |
| if name == 'accept': | |
| old['accept_outputs'] = c.accept_outputs | |
| write(state, old) | |
| if c.segments is not None: | |
| report['segments'] = c.segments | |
| if executed or (index <= hi and old.get('rc') == 0 and old.get('inputs_sha') == key): | |
| report['stages'][name] = dict(status='failed' if old['rc'] else 'executed' if executed else 'reused', rc=old['rc']) | |
| if name == 'accept': | |
| report['outputs'] = old.get('accept_outputs', {}) | |
| if old['rc']: | |
| if name == 'generate' and c.segments and c.segments['complete']: | |
| report.update(status='partial', rc=old['rc'], failed_stage=name) | |
| report['stages'][name]['status'] = 'partial' | |
| else: | |
| report.update(status='failed', rc=old['rc'], failed_stage=name) | |
| write(report_path, report) | |
| record_trial(c, report, scope) | |
| print(old['stderr_tail'], file=sys.stderr, end='') | |
| return old['rc'] if old['rc'] > 0 else 1 | |
| if c.segments is not None and c.segments['shortfall']: | |
| report['rc'] = report['rc'] or 1 | |
| write(report_path, report) | |
| upstream = dict(inputs_sha=old.get('inputs_sha'), outputs=files(map(Path, old.get('outputs', [])))) | |
| if not report['rc'] and names[hi] == 'accept' and all(s['rc'] == 0 for s in report['stages'].values()): | |
| report['status'] = 'completed' | |
| write(report_path, report) | |
| record_trial(c, report, scope) | |
| return max(1, report['rc']) if report['rc'] else 0 | |