RoboHome / code /robohome /src /tools /rplan /shell_check.py
RoboParty Release
Unify robohome source, assets and scenes delivery
3f15e9f
Raw History Blame
5 kB
#!/usr/bin/env python3
"""Build the native shell in Blender (the first stage of the chain, `scene_workflow.py build-shell`) for a random sample of a library, one
plan per case, and count how many build, are saved and re-read. This is the part of the chain that runs before furnishing.
shell_check.py --tree <code tree> --library lib.json --count 300 --out report.json [--seed 1] [--workers 8] [--keep]
shell_check.py ... --count 0 --workers 40 checks every plan (about 8 s of one core each); filter_library.py then keeps the ones that built
Needs the experiment driver of the chain (it supplies the environment, rootfs and Blender path). Each case is created under
<tree>/engine/runs/shellcheck_<tag>_<plan id> and removed again when it passed (--keep leaves it); failed cases are always kept."""
import sys
from pathlib import Path
sys.path.insert(0, str(Path(__file__).resolve().parents[2]))
import rhg_paths
import argparse
import json
import os
import random
import shutil
import subprocess
import sys
import time
from concurrent.futures import ThreadPoolExecutor
from pathlib import Path
DRIVER_DIR = os.environ.get('RHG_RPLAN_DRIVER_DIR', '${RHG_WORKSPACE_ROOT}/random_e2e_20261104/driver')
def build_one(job):
driver, tree, plan, library_dir, tag, keep = job
pid = plan['plan_id']
case = tree / 'engine/runs' / ('shellcheck_%s_%s' % (tag, pid))
corpus = library_dir / (pid + '.json')
corpus.write_text(json.dumps({'schema': 'robohousegen.rplan_seed_file.single', 'plan_count': 1, 'plans': [plan]}))
env = driver.environment(tree, case)
if 'RHG_DIGEST_CACHE' in os.environ:
env['RHG_DIGEST_CACHE'] = os.environ['RHG_DIGEST_CACHE']
env['RHG_RPLAN_SEEDS'] = str(corpus)
config = driver.load(driver.CONFIG)
command = ['/usr/bin/python3', '-B', '-u', str(tree / 'scene_workflow.py'), 'build-shell', '--case', str(case), '--rootfs', config['rootfs'],
'--seed', '1', '--blender', driver.BLENDER]
started = time.time()
run = subprocess.run(command, cwd=tree, env=env, stdin=subprocess.DEVNULL, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True, timeout=600)
result = {}
try:
result = json.loads((case / 'native_shell_result.json').read_text())
except (OSError, ValueError):
pass
passed = run.returncode == 0 and result.get('passed') is True
row = dict(plan_id=pid, passed=passed, returncode=run.returncode, seconds=round(time.time() - started, 1), status=result.get('status'),
tail='' if passed else run.stdout[-600:])
if passed and not keep:
shutil.rmtree(case, ignore_errors=True)
corpus.unlink()
return row
def main():
ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
ap.add_argument('--tree', required=True, type=Path)
ap.add_argument('--library', required=True, type=Path)
ap.add_argument('--count', type=int, default=200, help='how many plans to draw at random; 0 = every plan of the library')
ap.add_argument('--seed', type=int, default=1)
ap.add_argument('--workers', type=int, default=8)
ap.add_argument('--out', required=True, type=Path)
ap.add_argument('--keep', action='store_true', help='keep the cases that built')
args = ap.parse_args()
args.out, args.library = args.out.resolve(), args.library.resolve() # the builds run in another directory
sys.path.insert(0, rhg_paths.resolve(DRIVER_DIR))
import run_random_e2e_v6 as driver
plans = json.loads(args.library.read_text())['plans']
chosen = plans if args.count == 0 else random.Random(args.seed).sample(plans, min(args.count, len(plans)))
tag = '%d' % int(time.time())
scratch = args.out.parent / (args.out.stem + '_corpora')
scratch.mkdir(parents=True, exist_ok=True)
tree = args.tree.resolve()
rows = []
progress = args.out.with_suffix('.jsonl') # one line per finished plan, so a stopped run keeps what it did
with ThreadPoolExecutor(args.workers) as pool, progress.open('w') as log:
for row in pool.map(build_one, [(driver, tree, p, scratch, tag, args.keep) for p in chosen]):
rows.append(row)
log.write(json.dumps(row) + '\n')
log.flush()
if len(rows) % 1000 == 0:
print('%d of %d done, %d failed so far' % (len(rows), len(chosen), sum(1 for r in rows if not r['passed'])), flush=True)
scratch.rmdir()
failed = [r for r in rows if not r['passed']]
args.out.write_text(json.dumps(dict(tree=str(tree), library=str(args.library), count=len(rows), passed=len(rows) - len(failed), rows=rows), indent=1))
print('%d of %d shells built, saved and re-read (median %.1f s)' % (len(rows) - len(failed), len(rows), sorted(r['seconds'] for r in rows)[len(rows) // 2]))
for row in failed[:10]:
print('FAILED', row['plan_id'], row['returncode'], row['tail'][-200:].replace('\n', ' | '))
if __name__ == '__main__':
main()