#!/usr/bin/env python3
"""Run independent read-only checks on one bench-exec snapshot.

Callers must select checks that can safely coexist: no source writes, shared
output artifacts, migrations, or dependent commands. This is scheduling, not
a validator or a correctness certificate. Every exit status/output is retained.
"""
import json
import os
import shlex
import sys

RUNNER = r'''
import json, subprocess, sys, tempfile, time
commands = json.loads(sys.argv[1])
jobs = []
try:
    for command in commands:
        log = tempfile.TemporaryFile()
        try:
            process = subprocess.Popen(['bash', '-c', command], stdout=log, stderr=subprocess.STDOUT)
        except BaseException:
            log.close()
            raise
        jobs.append((command, process, log, time.monotonic()))
    failed = False
    # Poll to report completions promptly while preserving each complete log.
    pending = list(jobs)
    while pending:
        for job in list(pending):
            command, process, log, started = job
            code = process.poll()
            if code is None:
                continue
            print(json.dumps({'command': command, 'exit_code': code,
                              'seconds': round(time.monotonic()-started, 3)}), flush=True)
            log.seek(0)
            while True:
                chunk = log.read(65536)
                if not chunk: break
                sys.stdout.buffer.write(chunk)
            sys.stdout.buffer.write(b'\n')
            sys.stdout.buffer.flush()
            failed |= code != 0
            pending.remove(job)
        if pending: time.sleep(.02)
finally:
    for _, process, log, _ in jobs:
        if process.poll() is None: process.terminate()
        try: process.wait(timeout=5)
        except subprocess.TimeoutExpired:
            process.kill()
            process.wait()
        log.close()
sys.exit(1 if failed else 0)
'''

if __name__ == '__main__':
    commands = sys.argv[1:]
    if not 1 <= len(commands) <= 2 or any(not c.strip() for c in commands):
        sys.exit('usage: bench-validate "independent read-only check" ["independent read-only check"]')
    command = 'python3 -c ' + shlex.quote(RUNNER) + ' ' + shlex.quote(json.dumps(commands))
    # Preserve bench-exec's signal handling and workspace lock, with one sync.
    os.execvp('bench-exec', ['bench-exec', command])
