"""Run the original lab in a fresh POSIX evidence directory; never install tools.""" from pathlib import Path from datetime import datetime, timezone import argparse import hashlib import json import os import re import shutil import signal import subprocess import time def group_alive(pgid): # macOS can briefly return EPERM while a reaped process group disappears. # Retry that ambiguity; persistent EPERM conservatively means not cleared. for attempt in range(5): try: os.killpg(pgid, 0) return True except ProcessLookupError: return False except PermissionError: if attempt == 4: return True time.sleep(0.01) def stop_owned_group(child): """TERM, reap/check, then KILL only the session created for this child.""" for sig in (signal.SIGTERM, signal.SIGKILL): if group_alive(child.pid): try: os.killpg(child.pid, sig) except (ProcessLookupError, PermissionError): pass deadline = time.monotonic() + 2 while time.monotonic() < deadline: child.poll() if not group_alive(child.pid): return False time.sleep(0.05) child.poll() return group_alive(child.pid) def main(): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument('--godot', required=True, help='Exact Godot executable') parser.add_argument('--output', type=Path, required=True, help='Must not exist') args = parser.parse_args() if os.name != 'posix': parser.error('This bounded process-group wrapper is POSIX-only; use your platform runner.') root = Path(__file__).resolve().parent.parent source = root / 'examples/godot_workshop' out = args.output.resolve() out.mkdir(parents=True, exist_ok=False) print(json.dumps({'owned_pid': os.getpid(), 'pgid': os.getpgid(0), 'output': str(out), 'stage_timeout_seconds': 20}), flush=True) project = out / 'project' shutil.copytree(source, project, ignore=shutil.ignore_patterns('.godot', '__pycache__')) manifest = [{'path': str(p.relative_to(source)), 'bytes': p.stat().st_size, 'sha256': hashlib.sha256(p.read_bytes()).hexdigest()} for p in sorted(source.rglob('*')) if p.is_file() and '.godot' not in p.parts and p.suffix != '.pyc'] (out / 'source.json').write_text(json.dumps(manifest, indent=2) + '\n') version = subprocess.Popen([args.godot, '--headless', '--version'], stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True, start_new_session=True) print(json.dumps({'stage': 'version', 'owned_pid': version.pid, 'pgid': version.pid, 'timeout_seconds': 5}), flush=True) try: version_stdout, version_stderr = version.communicate(timeout=5) except subprocess.TimeoutExpired: remaining = stop_owned_group(version) (out / 'version-error.json').write_text(json.dumps({ 'classification': 'INVALID', 'reason': 'version timeout', 'owned_pid': version.pid, 'owned_group_remaining': remaining}, indent=2) + '\n') return 1 version_remaining = group_alive(version.pid) if version.returncode != 0 or version_remaining: remaining = stop_owned_group(version) if version_remaining else False (out / 'version-error.json').write_text(json.dumps({ 'classification': 'INVALID', 'reason': 'version command failed or left a child', 'exit_code': version.returncode, 'stderr': version_stderr, 'owned_pid': version.pid, 'owned_group_remaining': remaining}, indent=2) + '\n') return 1 report = {'engine': version_stdout.strip(), 'started_at_utc': datetime.now(timezone.utc).isoformat(), 'runner_sha256': hashlib.sha256(Path(__file__).read_bytes()).hexdigest(), 'source_files': manifest, 'runs': [], 'scope': 'Headless domain, parsed input, layout geometry and PCM only; no visual/listening/device acceptance'} bad_log = re.compile(r'SCRIPT ERROR|Parse Error|ERROR:|ObjectDB instances leaked|resources still in use', re.I) for stage, flags in [('import', ['--import']), ('tests', ['--script', 'res://tests/run_tests.gd'])]: command = [args.godot, '--headless', '--audio-driver', 'Dummy', '--path', str(project)] + flags with (out / (stage + '.log')).open('xb') as log: child = subprocess.Popen(command, stdout=log, stderr=subprocess.STDOUT, start_new_session=True) print(json.dumps({'stage': stage, 'owned_pid': child.pid, 'pgid': child.pid, 'timeout_seconds': 20}), flush=True) timed_out = False try: code = child.wait(timeout=20) except subprocess.TimeoutExpired: timed_out = True stop_owned_group(child) code = child.poll() log_text = (out / (stage + '.log')).read_text(errors='replace') cleanup_required = group_alive(child.pid) group_remaining = stop_owned_group(child) if cleanup_required else False run = {'stage': stage, 'command': command, 'owned_pid': child.pid, 'exit_code': code, 'timed_out': timed_out, 'log_errors': bad_log.findall(log_text), 'cleanup_required': cleanup_required, 'owned_group_remaining': group_remaining} report['runs'].append(run) print(json.dumps(run), flush=True) if code != 0 or timed_out or run['log_errors'] or cleanup_required: break if stage == 'tests': lines = [line[len('LAB_RESULT '):] for line in log_text.splitlines() if line.startswith('LAB_RESULT ')] if len(lines) == 1: report['lab_result'] = json.loads(lines[0]) ok = len(report['runs']) == 2 and all(r['exit_code'] == 0 and not r['timed_out'] and not r['log_errors'] and not r['cleanup_required'] and not r['owned_group_remaining'] for r in report['runs']) ok = ok and bool(report.get('lab_result')) and not report.get('lab_result', {}).get('failures', ['missing marker']) report['classification'] = 'PASS' if ok else ('INVALID' if any(r['timed_out'] or r['cleanup_required'] or r['owned_group_remaining'] for r in report['runs']) else 'FAIL') (out / 'report.json').write_text(json.dumps(report, ensure_ascii=False, indent=2) + '\n') print(report['classification'], flush=True) return 0 if ok else 1 if __name__ == '__main__': raise SystemExit(main())