slime/search/test_search.py

111 lines
5.3 KiB
Python

#!/usr/bin/env python3
"""Persistence integration tests with a deterministic fake GPU backend."""
import json
import os
from pathlib import Path
import signal
import sqlite3
import subprocess
import sys
import tempfile
import time
import unittest
SEARCH = Path(__file__).with_name('slime-search.py')
FAKE = r'''#!/usr/bin/env python3
import json, os, pathlib, sys, time
args = dict(zip(sys.argv[1::2], sys.argv[2::2]))
r = int(args['--radius']); total = 1+2*r*(r+1)
x = int(args['--x']); z = int(args['--z'])
p = args['--pattern'].strip().replace('\n','/').split('/')
out = dict(center=[x,z],radius_chunks=r,pattern=p,anchors=total,mode='ordinary_all_effective_seeds',rejection_tail_included=False)
if '--dry-run' not in sys.argv:
start=int(args['--start-anchor']); count=int(args['--anchor-count'])
if os.environ.get('PAUSE_AT') == str(start):
pathlib.Path(os.environ['MARKER']).touch()
time.sleep(60)
limit=int(args['--max-results'])
out.update(start_anchor=start,anchor_count=count,rounds=[dict(matches=count,sample_truncated=count>limit,sample=[[i,x,z] for i in range(start,start+min(count,limit))],gpus=[dict(anchors=count)])])
print(json.dumps(out))
'''
class SearchTests(unittest.TestCase):
def setUp(self):
self.tmp = tempfile.TemporaryDirectory()
self.addCleanup(self.tmp.cleanup)
self.root = Path(self.tmp.name)
self.fake = self.root / 'bench'
self.fake.write_text(FAKE)
self.fake.chmod(0o755)
self.state = self.root / 'state.sqlite'
self.command = [sys.executable, str(SEARCH), '--bench', str(self.fake), '--state', str(self.state)]
def run_search(self, *args, ok=True):
p = subprocess.run(self.command + list(args), capture_output=True, text=True, timeout=15)
self.assertEqual(p.returncode == 0, ok, p.stderr)
return p
def test_complete_resume_export_and_mismatch(self):
result = self.run_search('--radius', '2', '--checkpoint-anchors', '4')
self.assertEqual(json.loads(result.stdout)['matches'], 13)
self.fake.unlink() # Completed resume and status need no GPU executable.
self.assertTrue(json.loads(self.run_search().stdout)['completed'])
output = self.root / 'results.jsonl'
self.run_search('--export', str(output))
self.assertEqual([json.loads(line)[0] for line in output.read_text().splitlines()], list(range(13)))
self.run_search('--export', str(output), ok=False)
self.fake.write_text(FAKE)
self.fake.chmod(0o755)
self.assertIn('differs', self.run_search('--radius', '3', ok=False).stderr)
self.assertEqual(json.loads(self.run_search('--status').stdout)['next_anchor'], 13)
def test_truncation_splits_without_losing_results(self):
result = self.run_search('--radius', '2', '--max-results', '2')
self.assertEqual(json.loads(result.stdout)['matches'], 13)
with sqlite3.connect(self.state) as db:
self.assertEqual(db.execute('SELECT count(*) FROM matches').fetchone()[0], 13)
def test_sigkill_and_exclusive_lock(self):
marker = self.root / 'paused'
env = dict(os.environ, PAUSE_AT='4', MARKER=str(marker))
with subprocess.Popen(self.command + ['--radius', '2', '--checkpoint-anchors', '4'],
env=env, start_new_session=True, stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL) as child:
try:
deadline = time.monotonic() + 10
while not marker.exists():
if child.poll() is not None or time.monotonic() > deadline:
self.fail('backend did not reach the second batch')
time.sleep(.02)
self.assertIn('already in use', self.run_search(ok=False).stderr)
os.killpg(child.pid, signal.SIGKILL)
child.wait()
finally:
if child.poll() is None:
os.killpg(child.pid, signal.SIGKILL)
child.wait()
self.assertEqual(json.loads(self.run_search('--status').stdout)['next_anchor'], 4)
self.assertEqual(json.loads(self.run_search().stdout)['matches'], 13)
with sqlite3.connect(self.state) as db:
self.assertEqual(db.execute('SELECT count(*) FROM matches').fetchone()[0], 13)
def test_transaction_failure_rolls_back_results(self):
# Abort the progress update after results have been inserted.
self.run_search('--radius', '0')
with sqlite3.connect(self.state) as db:
state = json.loads(db.execute('SELECT value FROM state').fetchone()[0])
state.update(next_anchor=0, matches=0)
db.execute('DELETE FROM matches')
db.execute('UPDATE state SET value=?', (json.dumps(state),))
db.execute("CREATE TRIGGER fail_progress BEFORE UPDATE ON state BEGIN SELECT RAISE(ABORT, 'simulated disk failure'); END")
self.run_search(ok=False)
with sqlite3.connect(self.state) as db:
self.assertEqual(db.execute('SELECT count(*) FROM matches').fetchone()[0], 0)
self.assertEqual(json.loads(db.execute('SELECT value FROM state').fetchone()[0])['next_anchor'], 0)
db.execute('DROP TRIGGER fail_progress')
self.assertEqual(json.loads(self.run_search().stdout)['matches'], 1)
if __name__ == '__main__':
unittest.main()