From 2b80f804af4a93bd017ca32baec2233d1d0039de Mon Sep 17 00:00:00 2001 From: claude Date: Sat, 10 Oct 2026 22:08:13 +0200 Subject: [PATCH] Add Django integration tests for the pipeline scheduler --- OpenBench/tests_pipelines.py | 430 +++++++++++++++++++++++++++++++++++ 1 file changed, 430 insertions(+) create mode 100644 OpenBench/tests_pipelines.py diff --git a/OpenBench/tests_pipelines.py b/OpenBench/tests_pipelines.py new file mode 100644 index 0000000..31466e3 --- /dev/null +++ b/OpenBench/tests_pipelines.py @@ -0,0 +1,430 @@ +# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # +# # +# OpenBench is a chess engine testing framework authored by Andrew Grant. # +# # +# # +# OpenBench is free software: you can redistribute it and/or modify # +# it under the terms of the GNU General Public License as published by # +# the Free Software Foundation, either version 3 of the License, or # +# (at your option) any later version. # +# # +# OpenBench is distributed in the hope that it will be useful, # +# but WITHOUT ANY WARRANTY; without even the implied warranty of # +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # +# GNU General Public License for more details. # +# # +# You should have received a copy of the GNU General Public License # +# along with this program. If not, see . # +# # +# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # + + +# Run with: python3 manage.py test OpenBench +# +# Exercises the Pipeline scheduler against a real ( test ) database. Creating a +# workload normally verifies it against the Github API, which is replaced here +# by a stand-in that only saves the Test. Everything else is the real thing. + +import unittest + +from datetime import timedelta +from unittest import mock + +from django.contrib.auth.models import User +from django.core.exceptions import ValidationError +from django.test import TestCase +from django.utils import timezone + +import OpenBench.pipelines as pipelines + +from OpenBench.models import Engine, LogEvent, Pipeline, PipelineRun, Profile, StepRun, Test + +# Older Test models keep the SPSA settings in a field, newer ones in another table +HAS_SPSA = any(field.name == 'spsa' for field in Test._meta.get_fields()) + +def payload(**changes): + + data = { + 'dev_engine' : 'Stockfish', 'dev_repo' : 'https://github.com/o/r', 'dev_branch' : 'dev', + 'dev_network' : '', 'dev_options' : 'Threads=1 Hash=8', 'dev_time_control' : '8.0+0.08', + 'base_engine' : 'Stockfish', 'base_repo' : 'https://github.com/o/r', 'base_branch' : 'master', + 'base_network' : '', 'base_options' : 'Threads=1 Hash=8', 'base_time_control' : '8.0+0.08', + 'book_name' : 'UHO.epd', 'upload_pgns' : 'FALSE', 'priority' : '0', 'throughput' : '1000', + 'syzygy_wdl' : 'OPTIONAL', 'syzygy_adj' : 'OPTIONAL', + 'win_adj' : 'movecount=3 score=400', 'draw_adj' : 'movenumber=40 movecount=8 score=10', + 'workload_size' : '32', 'test_mode' : 'SPRT', + 'test_bounds' : '[0.00, 2.00]', 'test_confidence' : '[0.10, 0.10]', + } + + data.update(changes) + return data + +def step(name, kind='TEST', **changes): + return { 'name' : name, 'kind' : kind, 'payload' : payload(**changes) } + +def tune_step(name): + + data = { k : v for k, v in payload().items() if not k.startswith('base_') } + for key in ('workload_size', 'test_mode', 'test_bounds', 'test_confidence'): del data[key] + + data.update({ + 'spsa_alpha' : '0.602', 'spsa_gamma' : '0.101', 'spsa_A_ratio' : '0.1', + 'spsa_iterations' : '2', 'spsa_pairs_per' : '1', + 'spsa_reporting_type' : 'BULK', 'spsa_distribution_type' : 'SINGLE', + 'spsa_inputs' : 'Aspiration, int, 20, 5, 50, 4, 0.002' }) + + return { 'name' : name, 'kind' : 'TUNE', 'payload' : data } + +def graph(**changes): + + data = { + 'version' : 1, 'start' : 'stc', + 'steps' : { 'stc' : step('STC'), 'ltc' : step('LTC', dev_time_control='40.0+0.40'), 'retry' : step('Retry') }, + 'edges' : [ + { 'from' : 'stc', 'on' : 'passed', 'to' : 'ltc', 'set' : { 'priority' : '5' } }, + { 'from' : 'stc', 'on' : 'failed', 'to' : 'retry' }, + ], + } + + data.update(changes) + return data + +class FakeCreator(object): + + """ Stands in for create_new_test / create_new_tune / create_new_datagen """ + + def __init__(self, errors=None, explode=False, mode='SPRT'): + self.calls, self.errors, self.explode, self.mode = [], errors, explode, mode + + def __call__(self, request): + + self.calls.append(request) + + if self.explode: raise RuntimeError('Github is down') + if self.errors : return None, list(self.errors) + + engine = Engine.objects.first() + post = request.POST + + extra = { 'spsa' : { 'pairs_per' : 1, 'iterations' : 2 } } if self.mode == 'SPSA' and HAS_SPSA else {} + + test = Test.objects.create( + author=request.user.username, book_name=post['book_name'], + dev=engine, dev_repo=post['dev_repo'], dev_engine=post['dev_engine'], + dev_options=post['dev_options'], dev_time_control=post['dev_time_control'], + base=engine, base_repo=post.get('base_repo', ''), base_engine=post.get('base_engine', ''), + base_options=post.get('base_options', ''), base_time_control=post.get('base_time_control', ''), + priority=int(post['priority']), throughput=int(post['throughput']), + test_mode=self.mode, **extra) + + return test, None + +class PipelineTestCase(TestCase): + + def setUp(self): + + self.engine = Engine.objects.create(name='dev', source='x', sha='0' * 40, bench=1) + self.user = User.objects.create_user('alice', 'a@example.com', 'pw') + self.profile = Profile.objects.create(user=self.user, enabled=True, approver=True) + + self.creator = FakeCreator() + patches = [ + mock.patch('OpenBench.workloads.create_workload.create_new_test' , self.creator), + mock.patch('OpenBench.workloads.create_workload.create_new_tune' , self.creator), + mock.patch('OpenBench.workloads.create_workload.create_new_datagen', self.creator), + ] + + for patch in patches: + patch.start(); self.addCleanup(patch.stop) + + # Helpers + + def pipeline(self, **changes): + return Pipeline.objects.create(name='P', author='alice', graph=changes.pop('graph', graph()), **changes) + + def start(self, **kwargs): + run, issues = pipelines.start_pipeline(self.pipeline(**kwargs)) + self.assertIsNotNone(run, issues) + return run + + def steps(self, run): + return { s.step_key : s for s in StepRun.objects.filter(run=run).order_by('id') } + + def finish(self, step_run, passed=False, failed=False, deleted=False, finished=True): + + test = Test.objects.get(id=step_run.test_id) + test.finished, test.passed, test.failed, test.deleted = finished, passed, failed, deleted + test.save() + + pipelines.workload_finished(test.id, background=False) + + def keys(self, run): + return [s.step_key for s in StepRun.objects.filter(run=run).order_by('id')] + + def status(self, run): + return PipelineRun.objects.get(id=run.id).status + +class StartingTests(PipelineTestCase): + + def test_start_creates_the_first_workload(self): + + run = self.start() + first = self.steps(run)['stc'] + + self.assertEqual((first.status, run.status, run.fired), ('RUNNING', 'RUNNING', 1)) + self.assertTrue(Test.objects.filter(id=first.test_id, author='alice').exists()) + self.assertEqual(self.creator.calls[0].POST['dev_branch'], 'dev') + + def test_invalid_graph_never_starts(self): + + bad = graph(start='nope') + run, issues = pipelines.start_pipeline(self.pipeline(graph=bad)) + + self.assertIsNone(run) + self.assertEqual(PipelineRun.objects.count(), 0) + self.assertTrue(any(i['code'] == 'start.missing' for i in issues)) + + def test_disabled_pipeline_never_starts(self): + run, issues = pipelines.start_pipeline(self.pipeline(enabled=False)) + self.assertIsNone(run) + + def test_invalid_graphs_cannot_be_saved_through_forms(self): + with self.assertRaises(ValidationError): + Pipeline(name='x', author='alice', graph={}).full_clean() + + def test_run_works_from_a_snapshot(self): + + pipeline = self.pipeline() + run, _ = pipelines.start_pipeline(pipeline) + + pipeline.graph['edges'] = []; pipeline.save() + self.finish(self.steps(run)['stc'], passed=True) + + self.assertEqual(self.keys(run), ['stc', 'ltc']) + +class BranchingTests(PipelineTestCase): + + def test_passed_starts_ltc_with_the_edge_overrides(self): + + run = self.start() + self.finish(self.steps(run)['stc'], passed=True) + + steps = self.steps(run) + self.assertEqual(self.keys(run), ['stc', 'ltc']) + self.assertEqual((steps['stc'].status, steps['ltc'].status, steps['ltc'].via), ('PASSED', 'RUNNING', 'passed')) + self.assertEqual(self.creator.calls[1].POST['dev_time_control'], '40.0+0.40') + self.assertEqual(self.creator.calls[1].POST['priority'], '5') + self.assertEqual(steps['ltc'].parent_id, steps['stc'].id) + self.assertEqual(self.status(run), 'RUNNING') + + def test_failed_starts_retry(self): + + run = self.start() + self.finish(self.steps(run)['stc'], failed=True) + self.assertEqual(self.keys(run), ['stc', 'retry']) + + def test_a_run_completes_when_nothing_is_left(self): + + run = self.start() + self.finish(self.steps(run)['stc'], passed=True) + self.finish(self.steps(run)['ltc'], passed=True) + + self.assertEqual(self.status(run), 'COMPLETED') + self.assertEqual(PipelineRun.objects.get(id=run.id).fired, 2) + + def test_stopped_by_hand_has_no_edge_and_ends_the_run(self): + + run = self.start() + self.finish(self.steps(run)['stc']) + + self.assertEqual(self.steps(run)['stc'].status, 'STOPPED') + self.assertEqual(self.status(run), 'COMPLETED') + self.assertIn('no edge', ' '.join(PipelineRun.objects.get(id=run.id).notes)) + + def test_deleting_a_running_workload_counts_as_stopped(self): + + run = self.start() + self.finish(self.steps(run)['stc'], deleted=True, finished=False) + self.assertEqual(self.steps(run)['stc'].status, 'STOPPED') + + def test_a_workload_that_is_still_running_changes_nothing(self): + + run = self.start() + self.finish(self.steps(run)['stc'], finished=False) + + self.assertEqual(self.steps(run)['stc'].status, 'RUNNING') + self.assertEqual(self.keys(run), ['stc']) + + def test_fan_out_starts_every_branch(self): + + both = graph(); both['edges'].append({ 'from' : 'stc', 'on' : 'passed', 'to' : 'retry' }) + run = self.start(graph=both) + self.finish(self.steps(run)['stc'], passed=True) + + self.assertEqual(sorted(self.keys(run)), ['ltc', 'retry', 'stc']) + self.finish(self.steps(run)['ltc'], passed=True) + self.assertEqual(self.status(run), 'RUNNING') # retry is still going + + self.finish(self.steps(run)['retry'], failed=True) + self.assertEqual(self.status(run), 'COMPLETED') + + @unittest.skipUnless(HAS_SPSA, 'Test has no spsa field') + def test_completed_tune_passes(self): + + tune = graph(steps={ 'tune' : tune_step('Tune'), 'ltc' : step('LTC') }, start='tune', + edges=[{ 'from' : 'tune', 'on' : 'passed', 'to' : 'ltc' }]) + + self.creator.mode = 'SPSA' + run = self.start(graph=tune) + + test = Test.objects.get(id=self.steps(run)['tune'].test_id) + test.games, test.finished = 4, True # 2 * pairs_per * iterations + test.save() + pipelines.workload_finished(test.id, background=False) + + self.assertEqual(self.steps(run)['tune'].status, 'PASSED') + self.assertEqual(self.keys(run), ['tune', 'ltc']) + +class SafetyTests(PipelineTestCase): + + def test_the_hook_is_idempotent(self): + + run = self.start() + stc = self.steps(run)['stc'] + + self.finish(stc, passed=True) + pipelines.workload_finished(stc.test_id, background=False) + pipelines.workload_finished(stc.test_id, background=False) + + self.assertEqual(self.keys(run), ['stc', 'ltc']) + self.assertEqual(len(self.creator.calls), 2) + + def test_loops_are_capped(self): + + again = graph(max_visits=3); again['edges'] = [{ 'from' : 'stc', 'on' : 'failed', 'to' : 'stc' }] + run = self.start(graph=again) + + for _ in range(5): + running = StepRun.objects.filter(run=run, status='RUNNING').first() + if running is None: break + self.finish(running, failed=True) + + self.assertEqual(self.keys(run), ['stc', 'stc', 'stc']) + self.assertEqual(self.status(run), 'COMPLETED') + self.assertIn('limit of 3 runs', ' '.join(PipelineRun.objects.get(id=run.id).notes)) + + def test_total_workloads_are_capped(self): + + small = graph(max_steps=1) + run = self.start(graph=small) + self.finish(self.steps(run)['stc'], passed=True) + + self.assertEqual(self.keys(run), ['stc']) + self.assertIn('limit of 1 workloads', ' '.join(PipelineRun.objects.get(id=run.id).notes)) + + def test_a_workload_that_cannot_be_created_is_an_error(self): + + self.creator.errors = ['dev could not be found'] + run, _ = pipelines.start_pipeline(self.pipeline()) + + stc = self.steps(run)['stc'] + self.assertEqual((stc.status, run.status), ('ERROR', 'ERROR')) + self.assertIn('could not be found', stc.message) + + def test_an_exception_while_creating_is_contained(self): + + self.creator.explode = True + run, _ = pipelines.start_pipeline(self.pipeline()) + self.assertEqual(self.steps(run)['stc'].status, 'ERROR') + + def test_an_error_on_one_branch_lets_the_other_finish(self): + + both = graph(); both['edges'].append({ 'from' : 'stc', 'on' : 'passed', 'to' : 'retry' }) + run = self.start(graph=both) + + self.creator.errors = ['nope'] # Every following creation fails + self.finish(self.steps(run)['stc'], passed=True) + + self.assertEqual(self.status(run), 'ERROR') + self.assertEqual([s.status for s in StepRun.objects.filter(run=run).order_by('id')], ['PASSED', 'ERROR', 'ERROR']) + + def test_disabling_the_pipeline_stops_it_from_carrying_on(self): + + run = self.start() + Pipeline.objects.filter(id=run.pipeline_id).update(enabled=False) + self.finish(self.steps(run)['stc'], passed=True) + + self.assertEqual(self.keys(run), ['stc']) + self.assertEqual(self.status(run), 'CANCELLED') + + def test_an_author_who_is_no_longer_enabled_cannot_create(self): + + self.profile.enabled = False; self.profile.save() + run, _ = pipelines.start_pipeline(self.pipeline()) + + self.assertEqual(self.steps(run)['stc'].status, 'ERROR') + self.assertIn('not an enabled user', self.steps(run)['stc'].message) + self.assertEqual(self.creator.calls, []) + + def test_unrelated_workloads_are_ignored(self): + + other = Test.objects.create( + author='alice', book_name='b', dev=self.engine, dev_repo='r', dev_engine='e', dev_options='o', + dev_time_control='1+1', base=self.engine, base_repo='r', base_engine='e', base_options='o', + base_time_control='1+1', finished=True) + + with self.assertNumQueries(1): + pipelines.workload_finished(other.id, background=False) + +class CatchUpTests(PipelineTestCase): + + def test_resolves_a_workload_that_ended_unnoticed(self): + + run = self.start() + Test.objects.filter(id=self.steps(run)['stc'].test_id).update(finished=True, passed=True) # No hook + + self.assertEqual(self.keys(run), ['stc']) + found = pipelines.catch_up() + + self.assertEqual(found['resolved'], 1) + self.assertEqual(self.keys(run), ['stc', 'ltc']) + + def test_relaunches_an_abandoned_launch(self): + + run = self.start() + stc = self.steps(run)['stc'] + + # Pretend the process died while launching, long ago + old = timezone.now() - timedelta(seconds=pipelines.STALE_LAUNCH_SECONDS + 60) + StepRun.objects.filter(id=stc.id).update(status='LAUNCHING', test_id=0, updated=old) + calls = len(self.creator.calls) + + found = pipelines.catch_up() + + self.assertEqual(found['relaunched'], 1) + self.assertEqual(len(self.creator.calls), calls + 1) + self.assertEqual(self.steps(run)['stc'].status, 'RUNNING') + + def test_leaves_a_recent_launch_alone(self): + + run = self.start() + stc = self.steps(run)['stc'] + StepRun.objects.filter(id=stc.id).update(status='LAUNCHING', test_id=0) + + self.assertEqual(pipelines.catch_up()['relaunched'], 0) + + def test_does_nothing_when_all_is_well(self): + + self.start() + self.assertEqual(pipelines.catch_up(), { 'relaunched' : 0, 'resolved' : 0 }) + +class AuditTests(PipelineTestCase): + + def test_events_are_logged(self): + + run = self.start() + self.finish(self.steps(run)['stc'], passed=True) + + summaries = list(LogEvent.objects.values_list('summary', flat=True)) + self.assertTrue(any('STARTED' in s for s in summaries)) + self.assertTrue(any(s.endswith('stc PASSED') for s in summaries))