#!/usr/bin/env python3 """Crash-resumable ordinary-branch search; Python standard library only.""" import argparse import fcntl import json import os from pathlib import Path import signal import sqlite3 import subprocess import sys DEFAULT_BENCH = Path(__file__).resolve().parents[1] / 'bench/bin/slime-bench' def bench_report(command): with subprocess.Popen(command, stdout=subprocess.PIPE, text=True) as child: try: output, _ = child.communicate() except BaseException: child.kill() child.wait() raise if child.returncode: raise RuntimeError(f'bench exited with status {child.returncode}; progress unchanged') return json.loads(output) def scope_command(binary, config): return [str(binary), '--x', str(config['center'][0]), '--z', str(config['center'][1]), '--radius', str(config['radius_chunks']), '--pattern', '/'.join(config['pattern'])] def read_state(db): row = db.execute('SELECT value FROM state WHERE id=1').fetchone() return json.loads(row[0]) if row else None def commit_batch(db, state, report): """Publish results and next position in the same durable transaction.""" batch = report['rounds'][0] if report['start_anchor'] != state['next_anchor'] or batch['sample_truncated']: raise RuntimeError('incomplete or unexpected batch; progress unchanged') count = report['anchor_count'] if count <= 0 or count > state['config']['anchors'] - state['next_anchor']: raise RuntimeError('invalid batch coverage') if sum(gpu['anchors'] for gpu in batch['gpus']) != count: raise RuntimeError('incomplete batch coverage') if batch['matches'] != len(batch['sample']): raise RuntimeError('missing results; progress unchanged') updated = dict(state, next_anchor=state['next_anchor'] + count, matches=state['matches'] + batch['matches']) with db: db.executemany('INSERT INTO matches(seed48,chunk_x,chunk_z) VALUES(?,?,?)', batch['sample']) db.execute('UPDATE state SET value=? WHERE id=1', (json.dumps(updated),)) return updated def summary(state): return dict(completed=state['next_anchor'] == state['config']['anchors'], next_anchor=state['next_anchor'], anchors=state['config']['anchors'], matches=state['matches'], config=state['config']) def main(): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument('--state', required=True, type=Path, help='SQLite checkpoint and results file') parser.add_argument('--bench', type=Path, default=DEFAULT_BENCH) parser.add_argument('--x', type=int) parser.add_argument('--z', type=int) parser.add_argument('--radius', type=int) pattern = parser.add_mutually_exclusive_group() pattern.add_argument('--size', type=int) pattern.add_argument('--pattern') pattern.add_argument('--pattern-file', type=Path) parser.add_argument('--devices', default='0') parser.add_argument('--checkpoint-anchors', type=int, default=65536, help='maximum anchors per durable transaction (default 65536)') parser.add_argument('--max-results', type=int, default=100000, help='per-batch result buffer; truncated batches are split and retried') parser.add_argument('--position-batch', type=int, default=128) parser.add_argument('--job-batch', type=int, default=2048) parser.add_argument('--cache-classes', type=int, default=4096) mode = parser.add_mutually_exclusive_group() mode.add_argument('--status', action='store_true') mode.add_argument('--export', type=Path, help='export committed [seed48,x,z] JSONL; do not search') args = parser.parse_args() if args.checkpoint_anchors < 1 or not 1 <= args.max_results <= 1000000: parser.error('checkpoint-anchors must be positive; max-results must be 1..1000000') # flock is released by the OS even after SIGKILL; never delete the lock file. args.state.parent.mkdir(parents=True, exist_ok=True) with open(str(args.state) + '.lock', 'a') as lock: try: fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB) except BlockingIOError: raise RuntimeError('this state file is already in use') from None if not args.state.exists() and (args.status or args.export): raise RuntimeError('state file does not exist') db = sqlite3.connect(args.state) try: db.execute('PRAGMA journal_mode=DELETE') db.execute('PRAGMA synchronous=EXTRA') with db: db.execute('CREATE TABLE IF NOT EXISTS state(id INTEGER PRIMARY KEY CHECK(id=1), value TEXT NOT NULL)') db.execute('CREATE TABLE IF NOT EXISTS matches(seed48 INTEGER,chunk_x INTEGER,chunk_z INTEGER, PRIMARY KEY(seed48,chunk_x,chunk_z))') state = read_state(db) if state is not None and state.get('version') != 1: raise RuntimeError('unsupported checkpoint version') # Normalize patterns and validate all geometry through the same bench parser. has_scope = any(v is not None for v in (args.x, args.z, args.radius, args.size, args.pattern, args.pattern_file)) if state is None or has_scope: old = state['config'] if state else dict(center=[0, 0], radius_chunks=None, pattern=['#####'] * 5) radius = args.radius if args.radius is not None else old['radius_chunks'] if radius is None: parser.error('--radius is required for a new search') pattern_text = '/'.join(old['pattern']) if args.size is not None: if not 1 <= args.size <= 6: parser.error('--size must be 1..6') pattern_text = '/'.join(['#' * args.size] * args.size) if args.pattern is not None: pattern_text = args.pattern if args.pattern_file is not None: pattern_text = args.pattern_file.read_text() command = [str(args.bench), '--x', str(args.x if args.x is not None else old['center'][0]), '--z', str(args.z if args.z is not None else old['center'][1]), '--radius', str(radius), '--pattern', pattern_text, '--dry-run'] scope = bench_report(command) config = {k: scope[k] for k in ('center', 'radius_chunks', 'pattern', 'anchors', 'mode', 'rejection_tail_included')} if state and config != state['config']: raise RuntimeError('scope or pattern differs from checkpoint; use a different --state file') if state is None: state = dict(version=1, config=config, next_anchor=0, matches=0) with db: db.execute('INSERT INTO state VALUES(1,?)', (json.dumps(state),)) directory = os.open(args.state.parent, os.O_RDONLY | os.O_DIRECTORY) try: os.fsync(directory) finally: os.close(directory) if args.export: with args.export.open('x') as out: for row in db.execute('SELECT seed48,chunk_x,chunk_z FROM matches ORDER BY seed48,chunk_x,chunk_z'): out.write(json.dumps(row) + '\n') return if args.status: print(json.dumps(summary(state), ensure_ascii=False)) return command = scope_command(args.bench, state['config']) for name in ('devices', 'position_batch', 'job_batch', 'cache_classes', 'max_results'): command += ['--' + name.replace('_', '-'), str(getattr(args, name))] while state['next_anchor'] < state['config']['anchors']: count = min(args.checkpoint_anchors, state['config']['anchors'] - state['next_anchor']) while True: report = bench_report(command + ['--start-anchor', str(state['next_anchor']), '--anchor-count', str(count)]) if not report['rounds'][0]['sample_truncated']: break if count == 1: raise RuntimeError('one anchor exceeds --max-results; increase it and resume; progress unchanged') count = max(1, count // 2) print(f'result buffer full; retrying {count} anchors', file=sys.stderr, flush=True) state = commit_batch(db, state, report) print(f"saved: {state['next_anchor']}/{state['config']['anchors']} anchors, {state['matches']} matches", file=sys.stderr, flush=True) print(json.dumps(summary(state), ensure_ascii=False)) finally: db.close() def interrupted(signum, frame): raise KeyboardInterrupt if __name__ == '__main__': signal.signal(signal.SIGTERM, interrupted) try: main() except KeyboardInterrupt: print('interrupted; resume with the same --state file', file=sys.stderr) sys.exit(130) except (RuntimeError, OSError, ValueError, sqlite3.Error) as exc: print(f'error: {exc}', file=sys.stderr) sys.exit(1)