From 429b765657d65393d294a456707bf4e08151f731 Mon Sep 17 00:00:00 2001 From: claude Date: Sat, 10 Oct 2026 22:06:13 +0200 Subject: [PATCH] Add pipeline engine and management commands (start_pipeline, advance_pipelines) --- .../management/commands/advance_pipelines.py | 46 +++ .../management/commands/start_pipeline.py | 52 +++ OpenBench/pipelines.py | 325 ++++++++++++++++++ 3 files changed, 423 insertions(+) create mode 100644 OpenBench/management/commands/advance_pipelines.py create mode 100644 OpenBench/management/commands/start_pipeline.py create mode 100644 OpenBench/pipelines.py diff --git a/OpenBench/management/commands/advance_pipelines.py b/OpenBench/management/commands/advance_pipelines.py new file mode 100644 index 0000000..5aa8898 --- /dev/null +++ b/OpenBench/management/commands/advance_pipelines.py @@ -0,0 +1,46 @@ +# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # +# # +# 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 . # +# # +# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # + + +import time + +from django.core.management.base import BaseCommand + +class Command(BaseCommand): + + help = 'Resolve Pipeline steps that missed their notification, and retry interrupted launches' + + def add_arguments(self, parser): + parser.add_argument('--loop', type=int, default=0, metavar='SECONDS', + help='Keep running, checking again every SECONDS, instead of running once') + + def handle(self, *args, **options): + + import OpenBench.pipelines + + while True: + found = OpenBench.pipelines.catch_up() + self.stdout.write('relaunched=%(relaunched)d resolved=%(resolved)d' % found) + + if not options['loop']: + break + + self.stdout.flush() + time.sleep(options['loop']) diff --git a/OpenBench/management/commands/start_pipeline.py b/OpenBench/management/commands/start_pipeline.py new file mode 100644 index 0000000..56e6f26 --- /dev/null +++ b/OpenBench/management/commands/start_pipeline.py @@ -0,0 +1,52 @@ +# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # +# # +# 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 . # +# # +# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # + + +from django.core.management.base import BaseCommand, CommandError + +class Command(BaseCommand): + + help = 'Start a run of a Pipeline' + + def add_arguments(self, parser): + parser.add_argument('pipeline_id', type=int) + parser.add_argument('--user', default=None, help='Who started it. Defaults to the Pipeline author') + + def handle(self, *args, **options): + + import OpenBench.pipelines + from OpenBench.models import Pipeline + + pipeline = Pipeline.objects.filter(id=options['pipeline_id']).first() + if pipeline is None: + raise CommandError('No such Pipeline') + + run, issues = OpenBench.pipelines.start_pipeline(pipeline, options['user']) + + for entry in issues: + where = ' [%s]' % (entry['step']) if entry['step'] else '' + self.stdout.write('%s%s: %s' % (entry['level'].upper(), where, entry['message'])) + + if run is None: + raise CommandError('The Pipeline cannot run') + + self.stdout.write('Started run #%d (%s)' % (run.id, run.status)) + for step in run.steps.order_by('id'): + self.stdout.write(' %s: %s%s' % (step.step_key, step.status, ' ' + step.message if step.message else '')) diff --git a/OpenBench/pipelines.py b/OpenBench/pipelines.py new file mode 100644 index 0000000..40b1236 --- /dev/null +++ b/OpenBench/pipelines.py @@ -0,0 +1,325 @@ +# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # +# # +# 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 . # +# # +# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # + + +# The Pipeline scheduler: starts workloads, and decides what to start next once +# a workload ends. All of the decision making lives in OpenBench/pipeline_graph.py +# and is free of Django. This module only does the bookkeeping around it. +# +# How a run moves along: +# +# start_pipeline() queues the starting step, then launches it +# workload_finished() is called whenever a workload is over ( passed, +# failed, stopped, deleted ). Resolves its step, +# queues whatever the graph says comes next +# launch_step() creates the actual workload for a queued step, +# through the same code that the web forms use +# catch_up() safety net for anything the above missed +# +# Deciding happens inside a short transaction. Creating a workload talks to the +# Github API, so that always happens outside of any transaction, in order to not +# hold the database ( SQLite locks all of it ) while waiting on the network. + +import copy +import sys +import threading +import traceback + +from collections import Counter +from datetime import timedelta + +from django.contrib.auth.models import User +from django.db import connections, transaction +from django.utils import timezone + +import OpenBench.pipeline_graph as graphs + +from OpenBench.models import LogEvent, Pipeline, PipelineRun, Profile, StepRun, Test + +STALE_LAUNCH_SECONDS = 300 # A LAUNCHING step older than this was abandoned +QUEUED_GRACE_SECONDS = 30 # Give the hook this long, before catch_up() steps in +MAX_NOTES = 50 + +class PipelineRequest(object): + + """ Stands in for a Django request, so that workloads made by a Pipeline are + verified and created by exactly the code that the web forms use """ + + def __init__(self, user, post): + self.user = user + self.POST = post + self.FILES = {} + self.method = 'POST' + +def _log(author, summary, test_id=0): + LogEvent.objects.create(author=author, summary=summary[:128], log_file='', test_id=test_id) + +def _add_notes(run, notes): + run.notes = (list(run.notes or []) + list(notes))[-MAX_NOTES:] + +def _queue(run, fire, parent): + + # Caller holds the lock on run, and saves it + run.fired += 1 + + return StepRun.objects.create( + run=run, parent=parent, step_key=fire.step_key, + via=fire.via, kind=fire.kind, payload=fire.payload) + +def _refresh_run(run, halted=False): + + # Caller holds the lock on run + status = graphs.run_status(list(run.steps.values_list('status', flat=True))) + + if halted and status == 'COMPLETED': + status = 'CANCELLED' + + run.status = status + run.save() + + +# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # +# STARTING # +# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # + +def start_pipeline(pipeline, starter=None): + + """ Returns ( run, issues ). The run is None if the Pipeline cannot run """ + + issues = graphs.validate_graph(pipeline.graph) + + if not pipeline.enabled or pipeline.deleted: + issues.append(graphs.issue('error', 'pipeline.disabled', 'The pipeline is disabled')) + + if graphs.has_errors(issues): + return None, issues + + with transaction.atomic(): + run = PipelineRun.objects.create( + pipeline=pipeline, graph=copy.deepcopy(pipeline.graph), + starter=starter or pipeline.author) + _queue(run, graphs.initial_fire(run.graph), None) + run.save() + + _log(pipeline.author, 'PIPELINE #%d RUN #%d STARTED' % (pipeline.id, run.id)) + + launch_queued(run.id) + return PipelineRun.objects.get(id=run.id), issues + + +# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # +# LAUNCHING # +# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # + +def launch_queued(run_id): + for step_id in StepRun.objects.filter(run_id=run_id, status='QUEUED').order_by('id').values_list('id', flat=True): + launch_step(step_id) + +def launch_step(step_id): + + # Claim the step, so that the hook and catch_up() can never both create it + claimed = StepRun.objects.filter(id=step_id, status='QUEUED').update(status='LAUNCHING', updated=timezone.now()) + if claimed != 1: + return + + step = StepRun.objects.get(id=step_id) + pipeline = Pipeline.objects.get(id=step.run.pipeline_id) + + try: + workload, errors = _create_workload(step, pipeline) + except Exception: + traceback.print_exc(); sys.stdout.flush() + workload, errors = None, ['Unexpected error while creating the workload'] + + with transaction.atomic(): + + run = PipelineRun.objects.select_for_update().get(id=step.run_id) + + if errors: + step.status = 'ERROR' + step.message = ' / '.join(errors)[:512] + step.resolved = timezone.now() + _add_notes(run, ['Could not create "%s": %s' % (step.step_key, step.message)]) + + else: + step.status = 'RUNNING' + step.test_id = workload.id + + step.save() + _refresh_run(run, halted=not pipeline.enabled or pipeline.deleted) + + if errors: + _log(pipeline.author, 'PIPELINE #%d %s ERROR' % (pipeline.id, step.step_key)) + +def _create_workload(step, pipeline): + + # Imported late: the workload modules depend on OpenBench.utils, which in + # turn calls into this module when a workload ends. They must be entered by + # way of OpenBench.views, like the web server does, or they import in circles + import OpenBench.views + + from OpenBench.config import OPENBENCH_CONFIG + from OpenBench.workloads import create_workload as creation + + user = User.objects.filter(username=pipeline.author).first() + profile = Profile.objects.filter(user=user).first() if user else None + + if not profile or not profile.enabled: + return None, ['"%s" is not an enabled user' % (pipeline.author)] + + creators = { + 'TEST' : creation.create_new_test, + 'TUNE' : creation.create_new_tune, + 'DATAGEN' : creation.create_new_datagen, + } + + workload, errors = creators[step.kind](PipelineRequest(user, dict(step.payload))) + + if errors: + return None, errors + + # The same bookkeeping that create_workload() does after creating a workload + summary = 'CREATE P=%d TP=%d' % (workload.priority, workload.throughput) + _log(user.username, summary, workload.id) + + if not OPENBENCH_CONFIG['use_cross_approval'] and profile.approver: + workload.approved = True + workload.save() + + return workload, None + + +# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # +# ADVANCING # +# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # + +def workload_finished(test_id, background=True): + + """ Hook for everything that can end a workload. Safe to call for any + workload, at any time, as many times as you like, and never raises. + + Cheap for workloads that no Pipeline cares about, which is nearly all + of them. Otherwise carries on in a thread, since creating the next + workload needs the Github API, and the caller is often a Worker who + should not be kept waiting for that. """ + + try: + if not StepRun.objects.filter(test_id=test_id, status='RUNNING').exists(): + return + except Exception: + traceback.print_exc(); sys.stdout.flush() + return + + if not background: + return _advance(test_id, guarded=True) + + threading.Thread(target=_advance_in_thread, args=(test_id,), daemon=True).start() + +def _advance_in_thread(test_id): + try: _advance(test_id, guarded=True) + finally: connections.close_all() # Threads own their database connections + +def _advance(test_id, guarded=False): + + if guarded: + try: return _advance(test_id) + except Exception: + traceback.print_exc(); sys.stdout.flush() + return + + to_launch = [] + + with transaction.atomic(): + + step = StepRun.objects.select_for_update().filter(test_id=test_id, status='RUNNING').first() + test = Test.objects.filter(id=test_id).first() + + if step is None or test is None: + return # Already handled, or nothing that we know of + + outcome = graphs.classify_outcome( + test.finished, test.deleted, test.passed, test.failed, + test.test_mode, test.games, getattr(test, 'spsa', None)) + + if outcome is None: + return # Still going + + run = PipelineRun.objects.select_for_update().get(id=step.run_id) + pipeline = Pipeline.objects.get(id=run.pipeline_id) + halted = not pipeline.enabled or pipeline.deleted + + step.status = outcome.upper() + step.resolved = timezone.now() + step.save() + + _log(pipeline.author, 'PIPELINE #%d %s %s' % (pipeline.id, step.step_key, outcome.upper()), test_id) + + if run.status != 'RUNNING': + pass # Nothing may start from a run that is already over + + elif halted: + _add_notes(run, ['Pipeline is disabled, not carrying on after "%s"' % (step.step_key)]) + + else: + visits = Counter(run.steps.values_list('step_key', flat=True)) + plan = graphs.plan_next(run.graph, step.step_key, outcome, visits, run.fired) + + _add_notes(run, plan.notes) + to_launch = [_queue(run, fire, step) for fire in plan.fires] + + _refresh_run(run, halted) + + for queued in to_launch: + launch_step(queued.id) + + +# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # +# SAFETY NET # +# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # + +def catch_up(): + + """ Picks up whatever the hooks could not: the server was down when a + workload ended, a thread died halfway, a launch was interrupted. Safe + to run at any time, and as often as you like. Returns what it found. """ + + now = timezone.now() + found = { 'relaunched' : 0, 'resolved' : 0 } + + # A launch that started, but never reported back. Whether or not the + # workload got created, there is no way to know here. A duplicate is much + # better than a pipeline that silently stalls, so it gets queued again. + stale = now - timedelta(seconds=STALE_LAUNCH_SECONDS) + StepRun.objects.filter(status='LAUNCHING', test_id=0, updated__lt=stale).update(status='QUEUED') + + waiting = now - timedelta(seconds=QUEUED_GRACE_SECONDS) + for step_id in StepRun.objects.filter(status='QUEUED', updated__lt=waiting).order_by('id').values_list('id', flat=True): + launch_step(step_id) + found['relaunched'] += 1 + + # Workloads that are over, but whose Step was never told so + running = StepRun.objects.filter(status='RUNNING', test_id__gt=0) + for test_id in list(running.values_list('test_id', flat=True)): + before = StepRun.objects.filter(test_id=test_id, status='RUNNING').exists() + _advance(test_id, guarded=True) + after = StepRun.objects.filter(test_id=test_id, status='RUNNING').exists() + found['resolved'] += int(before and not after) + + return found