Compare commits

..
Author SHA1 Message Date
claude c998e8c0d6 Pipelines: tests for the New pipeline page
Covers the page, one branch and Enter, and what goes wrong, with the real
scheduler and routing underneath: the first test is made from what the page
filled in, a pass starts the next test with its own settings, anything else
ends the run, and a first test that cannot be made leaves no pipeline behind.

The engines of the config are swapped for one the tests know, so they do not
depend on what a server has set up. The page is read the way a browser reads
it, because the site minifies its pages.

The shared test client now sends X-Forwarded-Proto: https, like the proxy in
front of the site. With SECURE_SSL_REDIRECT on, as in OpenSite/settings.py,
every plain-http request of the test client is otherwise answered with a
redirect to https, and no page test can pass.
2026-10-15 11:16:14 +02:00
claude 8077809d0b Pipelines: New pipeline is one branch and Enter
The button now opens a page that asks for the dev branch and nothing else,
like Create Test does. The engine, repository, default network, time control,
options, bounds and base branch come from the same presets Create Test uses,
and the default plan is STC, then LTC if it passes. Presets, the base branch,
a name and the engine are there for whoever wants them, under More options.

Enter creates the pipeline and starts it. If the first test cannot be made
(a branch that does not exist, Github down) the pipeline is not left behind,
and the page comes back with the branch still typed in. Save without running
is the other button.

The flow editor stays as it was, and is one click away from the list and from
the new page, for retries, branching on a failure, tunes and datagen.
2026-10-14 20:29:02 +02:00
claude 48027f1142 Pipelines: the settings of a step, filled in the way Create Test fills them in
A pure module that turns an engine, a preset and a dev branch into every
setting a Test step needs: the repository and default network, the default
preset, then the chosen one, with both_ going to dev and base alike. With it
a pipeline only has to be told the dev branch, as a single test does.

What no preset can fill in is reported instead of guessed. Includes the unit
tests, which run without Django.
2026-10-13 21:28:35 +02:00
claude 0122ede0f6 Pipelines: a visual editor. The flow is drawn on a canvas, a + on every step adds what happens next, and the settings sit in a side panel like the Create Test form 2026-10-13 18:59:54 +02:00
claude faf719ca31 Pipelines: a preview endpoint that draws and checks a graph while it is being built 2026-10-13 18:58:35 +02:00
claude 2ed44ca053 Pipelines: create and edit pipelines from the web UI 2026-10-11 22:54:41 +02:00
claude 011add1f23 Wire the pipeline pages in: routes, sidebar link, styles, and the chip on a test's page 2026-10-11 22:37:47 +02:00
claude ea1fed2627 Add tests for the pipeline pages: permission matrix, actions, pages, live signature, chip 2026-10-11 22:37:12 +02:00
claude edfc43a2be Pipeline pages: views for the list, the pipeline and the run
Permissions decided in one place (can_manage), every change is a POST,
and every decision leaves an event behind.
2026-10-11 22:36:22 +02:00
claude 860bb6f0d2 Pipeline pages: pipeline and run templates 2026-10-11 22:35:35 +02:00
claude 752650fd31 Pipeline pages: end the new files with a newline 2026-10-11 22:34:57 +02:00
claude 55c38e6180 Pipeline pages: list view, template and live-update script
Restores the first part of the pipeline pages commit that was lost in the
rebase: the pipelines list template and the run page's live-update script.
2026-10-11 22:34:45 +02:00
14 changed files with 3968 additions and 1 deletions

No files matched your search

+227
View File
@@ -0,0 +1,227 @@
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
# #
# OpenBench is a chess engine testing framework authored by Andrew Grant. #
# <https://github.com/AndyGrant/OpenBench> <andrew@grantnet.us> #
# #
# 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 <http://www.gnu.org/licenses/>. #
# #
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
# The settings of a pipeline step, filled in the way that the Create Test page
# fills them in ( see create_workload.js ): the engine, its repository and its
# default network, then the "default" preset of the engine, then the preset that
# was asked for, where a "both_" setting goes to the dev and the base alike.
# That is what lets a pipeline ask for one thing only, the dev branch, just like
# a single test does.
#
# Pure Python, like the graph module: no Django, no database. Everything that
# comes from the server is handed in, so that all of it can be tested on its own
# ( see UnitTests/test_pipeline_defaults.py ).
import re
from OpenBench.pipeline_graph import ALLOWED_FIELDS, CONDITIONAL_FIELDS, REQUIRED_FIELDS
from OpenBench.pipeline_graph import DEFAULT_MAX_STEPS, DEFAULT_MAX_VISITS, SCHEMA_VERSION
# What the Create Test page starts out with, before any preset is applied
FORM_DEFAULTS = {
'upload_pgns' : 'FALSE', 'priority' : '0', 'throughput' : '1000',
'syzygy_wdl' : 'DISABLED', 'syzygy_adj' : 'OPTIONAL',
}
# Only for engines whose presets say nothing about them, instead of a blank that can never run
FALLBACKS = {
'workload_size' : '32',
'win_adj' : 'movecount=3 score=400',
'draw_adj' : 'movenumber=40 movecount=8 score=10',
}
# Required settings that are allowed to be empty: "no network"
BLANK_OK = ('dev_network', 'base_network')
# One word, no spaces or quotes. Whether it exists is for Github to say, later
BRANCH_PATTERN = re.compile(r'[^\s"\'\\\x00-\x1f\x7f]{1,255}')
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
# PRESETS #
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
def preset_names(engine_config):
""" The test presets of an engine, in the order that its config lists them """
return [name for name in (engine_config.get('test_presets') or {}) if name != 'default']
def _expand(settings):
""" ( key, value ) pairs, with both_x turned into dev_x and base_x """
pairs = []
for key, value in settings.items():
if key.startswith('both_'):
pairs.append(('dev_' + key[len('both_'):], value))
pairs.append(('base_' + key[len('both_'):], value))
else:
pairs.append((key, value))
return pairs
def preset_settings(engine_config, preset):
""" What choosing a preset sets, in the order that the page applies it """
presets = engine_config.get('test_presets') or {}
pairs = _expand(presets.get('default') or {})
if preset != 'default':
pairs += _expand(presets.get(preset) or {})
return pairs
def time_control(engine_config, preset):
return str(dict(preset_settings(engine_config, preset)).get('dev_time_control', ''))
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
# NETWORKS #
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
def default_network(networks, engine):
""" The network that the page has selected for an engine: the last one flagged default """
chosen = ''
for network in networks:
if network.get('engine') == engine and network.get('default'):
chosen = network.get('sha256') or ''
return chosen
def find_network(networks, engine, wanted):
""" A preset may name a network, or give its hash. None when it is neither """
wanted = str(wanted)
if wanted in ('', 'None'):
return ''
found = None
for network in networks:
if network.get('engine') == engine and wanted in (network.get('name'), network.get('sha256')):
found = network.get('sha256') or ''
return found
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
# PAYLOAD #
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
def clean_branch(text):
""" The branch, or None if it cannot be one """
text = (text or '').strip()
return text if BRANCH_PATTERN.fullmatch(text) else None
def test_payload(engine, engine_config, preset, dev_branch, repos=None, networks=(), books=(), base_branch=''):
""" Returns ( payload, missing ): every setting of a Test step, as the Create
Test page would have it, and the names of the settings that nothing
could fill in. The payload may only be used when nothing is missing. """
repo = (repos or {}).get(engine) or engine_config.get('source') or ''
network = default_network(networks, engine)
payload = dict(FORM_DEFAULTS)
payload.update({
'dev_engine' : engine, 'base_engine' : engine,
'dev_repo' : repo, 'base_repo' : repo,
'dev_network' : network, 'base_network' : network,
})
mode = 'SPRT'
for key, value in preset_settings(engine_config, preset):
if key in ('dev_network', 'base_network'):
value = find_network(networks, engine, value)
if value is None: continue # Not one that exists. The page keeps what it had
# Like the page: the last of these that a preset sets decides the mode
if key == 'test_max_games': mode = 'GAMES'
if key in ('test_bounds', 'test_confidence'): mode = 'SPRT'
payload[key] = str(value)
for key, value in FALLBACKS.items():
if not str(payload.get(key, '')).strip():
payload[key] = value
if not str(payload.get('book_name', '')).strip():
payload['book_name'] = next(iter(books), '')
payload['test_mode'] = mode
payload['dev_branch'] = dev_branch
if base_branch:
payload['base_branch'] = base_branch
unused = ('test_max_games',) if mode == 'SPRT' else ('test_bounds', 'test_confidence')
payload = { key : value for key, value in payload.items() if key in ALLOWED_FIELDS and key not in unused }
required = REQUIRED_FIELDS['TEST'] + CONDITIONAL_FIELDS[mode]
missing = [key for key in required if key not in BLANK_OK and not str(payload.get(key, '')).strip()]
return payload, missing
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
# GRAPH #
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
def quick_graph(steps):
""" steps is [ ( name, payload ) ]. Each one starts when the one before it
passed. If anything else happens, the pipeline simply ends. """
graph = {
'version' : SCHEMA_VERSION, 'start' : 'step1',
'max_visits' : DEFAULT_MAX_VISITS, 'max_steps' : DEFAULT_MAX_STEPS,
'steps' : {}, 'edges' : [],
}
seen = {}
for index, (name, payload) in enumerate(steps, 1):
key = 'step%d' % (index)
seen[name] = seen.get(name, 0) + 1
label = name if seen[name] == 1 else '%s (%d)' % (name, seen[name])
graph['steps'][key] = { 'name' : label[:64], 'kind' : 'TEST', 'payload' : payload }
if index > 1:
graph['edges'].append({ 'from' : 'step%d' % (index - 1), 'on' : 'passed', 'to' : key })
return graph
def quick_name(dev_branch, names):
return ('%s: %s' % (dev_branch, ' then '.join(names)))[:128]
+791
View File
@@ -0,0 +1,791 @@
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
# #
# OpenBench is a chess engine testing framework authored by Andrew Grant. #
# <https://github.com/AndyGrant/OpenBench> <andrew@grantnet.us> #
# #
# 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 <http://www.gnu.org/licenses/>. #
# #
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
# The Pipeline pages: a list, the page of one Pipeline, and the page of one run.
#
# Who may do what, decided in one place ( can_manage ) and nowhere else:
# - Anybody with an enabled account may look at Pipelines and their runs
# - Only the author of a Pipeline, or an Approver, may start, pause, resume,
# or delete it, or cancel one of its runs
#
# Everything that changes something is a POST, which Django checks the CSRF token
# of, and takes no input from the request at all except which object it is for.
# Every decision, allowed or refused, leaves an event behind.
import OpenBench.config
import OpenBench.pipeline_defaults as defaults
import OpenBench.pipeline_graph as graphs
import OpenBench.pipeline_layout as drawing
import OpenBench.pipelines
import OpenBench.views
import copy
import json
from django.http import JsonResponse
from django.views.decorators.http import require_POST
from OpenBench.models import LogEvent, Network, Pipeline, PipelineRun, Profile, StepRun, Test
STATUS_LABELS = {
'QUEUED' : 'Waiting', 'LAUNCHING' : 'Starting', 'RUNNING' : 'Running',
'PASSED' : 'Passed', 'FAILED' : 'Failed', 'STOPPED' : 'Stopped',
'ERROR' : 'Could not start', 'COMPLETED' : 'Finished', 'CANCELLED' : 'Cancelled',
}
STATUS_BADGES = {
'QUEUED' : 'badge-muted', 'LAUNCHING' : 'badge-muted', 'RUNNING' : 'badge-info',
'PASSED' : 'badge-ok', 'FAILED' : 'badge-bad', 'STOPPED' : 'badge-warn',
'ERROR' : 'badge-bad', 'COMPLETED' : 'badge-ok', 'CANCELLED' : 'badge-warn',
}
WORKLOAD_PATHS = { 'TEST' : 'test', 'TUNE' : 'tune', 'DATAGEN' : 'datagen' }
WHEN = {
'passed' : 'it passes', 'failed' : 'it fails',
'stopped' : 'it is stopped', 'any' : 'it ends',
}
KIND_LABELS = { 'TEST' : 'Test', 'TUNE' : 'Tune', 'DATAGEN' : 'Datagen' }
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
# PERMISSIONS #
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
def viewer(request):
""" The Profile of whoever is asking, if they are logged in and enabled """
if not request.user.is_authenticated:
return None
profile = Profile.objects.select_related('user').filter(user=request.user).first()
return profile if profile and profile.enabled else None
def can_manage(profile, pipeline):
""" The one rule for changing a Pipeline or its runs. Closed by default """
if profile is None or not profile.enabled:
return False
return bool(profile.approver) or profile.user.username == pipeline.author
def _audit(username, summary):
LogEvent.objects.create(author=username, summary=summary[:128], log_file='', test_id=0)
def _turn_away(request, profile, pipeline_id=None, action=''):
""" Anonymous visitors go to log in. People who are logged in, but not
allowed, are told so, and it is written down. """
if not request.user.is_authenticated:
return OpenBench.views.redirect(request, '/login/', error=OpenBench.views.ERROR_MESSAGES['requires_login'])
if profile is None:
return OpenBench.views.redirect(request, '/index/', error=OpenBench.views.ERROR_MESSAGES['disabled'])
if pipeline_id is not None:
_audit(profile.user.username, 'PIPELINE #%d %s REFUSED' % (pipeline_id, action.upper()))
return OpenBench.views.redirect(request, '/pipelines/', error='Only the author of a pipeline, or an approver, can do that')
def _missing(request):
return OpenBench.views.redirect(request, '/pipelines/', error='That pipeline does not exist, or was deleted')
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
# PRESENTING #
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
def _status(status):
return { 'code' : status, 'label' : STATUS_LABELS.get(status, status.title()), 'badge' : STATUS_BADGES.get(status, 'badge-muted') }
def _step_name(graph, step_key):
return (graph.get('steps', {}).get(step_key) or {}).get('name') or step_key
def _leads(graph, step_key):
""" What a step leads to, in plain sentences """
sentences = []
for edge in graph.get('edges', []):
if edge['from'] != step_key:
continue
if edge['to'] is None:
what = 'the pipeline ends'
else:
what = 'start %s' % (_step_name(graph, edge['to']))
changes = len(edge.get('set') or {})
if changes:
what += ' with %d setting%s changed' % (changes, '' if changes == 1 else 's')
sentences.append('If %s, %s' % (WHEN.get(edge['on'], 'it ends'), what))
return sentences
def _describe_steps(graph):
rows = []
for step_key, step in graph['steps'].items():
what, speed = drawing.step_summary(step)
rows.append({
'key' : step_key, 'name' : step.get('name') or step_key,
'kind' : KIND_LABELS.get(step.get('kind'), step.get('kind')),
'what' : what, 'speed' : speed,
'leads' : _leads(graph, step_key),
'start' : step_key == graph.get('start'),
})
return rows
def _last_runs(pipelines):
latest = {}
for run in PipelineRun.objects.filter(pipeline__in=pipelines).order_by('-id'):
latest.setdefault(run.pipeline_id, run)
return latest
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
# PAGES #
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
def pipelines(request):
profile = viewer(request)
if profile is None:
return _turn_away(request, profile)
listed = list(Pipeline.objects.filter(deleted=False).order_by('-updated'))
latest = _last_runs(listed)
rows = []
for pipeline in listed:
run = latest.get(pipeline.id)
if not pipeline.enabled:
state = { 'code' : 'PAUSED', 'label' : 'Paused', 'badge' : 'badge-warn' }
elif run is not None:
state = _status(run.status)
else:
state = { 'code' : 'NEW', 'label' : 'Never run', 'badge' : 'badge-muted' }
rows.append({
'pipeline' : pipeline, 'run' : run, 'state' : state,
'steps' : len((pipeline.graph or {}).get('steps', {})),
})
data = {
'rows' : rows,
'running' : PipelineRun.objects.filter(status='RUNNING', pipeline__deleted=False).count(),
'paused' : sum(1 for row in rows if not row['pipeline'].enabled),
'total' : len(rows),
}
return OpenBench.views.render(request, 'pipelines.html', data)
def pipeline(request, id):
profile = viewer(request)
if profile is None:
return _turn_away(request, profile)
found = Pipeline.objects.filter(id=id, deleted=False).first()
if found is None:
return _missing(request)
issues = graphs.validate_graph(found.graph)
usable = not graphs.has_errors(issues) # A graph damaged behind our back is shown as damaged, not drawn
graph = found.graph if usable else None
names = { key : (step.get('name') or key) for key, step in graph['steps'].items() } if usable else {}
runs = list(PipelineRun.objects.filter(pipeline=found).order_by('-id')[:20])
for run in runs:
run.state = _status(run.status)
data = {
'pipeline' : found,
'can_manage' : can_manage(profile, found),
'svg' : drawing.render_svg(graph) if usable else '',
'steps' : _describe_steps(graph) if usable else [],
'usable' : usable,
'issues' : [dict(i, name=names.get(i['step'], i['step'])) for i in issues],
'runs' : runs,
'running' : next((run for run in runs if run.status == 'RUNNING'), None),
}
return OpenBench.views.render(request, 'pipeline.html', data)
def pipeline_run(request, run_id):
profile = viewer(request)
if profile is None:
return _turn_away(request, profile)
run = PipelineRun.objects.select_related('pipeline').filter(id=run_id).first()
if run is None:
return _missing(request)
graph = run.graph
steps = list(StepRun.objects.filter(run=run).order_by('id'))
approved = {
row['id'] : row['approved']
for row in Test.objects.filter(id__in=[s.test_id for s in steps if s.test_id]).values('id', 'approved')
}
states, hops, rows, keys = {}, [], [], {}
for step in steps:
keys[step.id] = step.step_key
state = states.setdefault(step.step_key, { 'runs' : 0 })
state['runs'] += 1
state['status'] = step.status
state['url'] = ('/%s/%d/' % (WORKLOAD_PATHS.get(step.kind, 'test'), step.test_id)) if step.test_id else None
if step.parent_id in keys:
hops.append((keys[step.parent_id], step.step_key, step.via))
rows.append({
'step' : step, 'name' : _step_name(graph, step.step_key), 'state' : _status(step.status),
'url' : state['url'],
'after' : ('After %s %s' % (_step_name(graph, keys[step.parent_id]), step.via)) if step.parent_id in keys else 'First step',
'waiting' : step.status == 'RUNNING' and approved.get(step.test_id) is False,
})
taken = graphs.followed_edges(graph, hops)
data = {
'run' : run,
'pipeline' : run.pipeline,
'state' : _status(run.status),
'can_manage' : can_manage(profile, run.pipeline),
'svg' : drawing.render_svg(graph, states=states, taken=taken),
'rows' : rows,
'signature' : '%s:%s' % (run.status, ','.join('%d=%s' % (s.id, s.status) for s in steps)),
'live' : run.status == 'RUNNING',
}
return OpenBench.views.render(request, 'pipeline_run.html', data)
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
# ACTIONS #
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
def _managed(request, id, action):
""" ( pipeline, None ) when this person may change it, ( None, response ) when not """
profile = viewer(request)
if profile is None:
return None, _turn_away(request, profile)
found = Pipeline.objects.filter(id=id, deleted=False).first()
if found is None:
return None, _missing(request)
if not can_manage(profile, found):
return None, _turn_away(request, profile, id, action)
return (found, profile), None
@require_POST
def pipeline_start(request, id):
managed, refusal = _managed(request, id, 'start')
if refusal: return refusal
found, profile = managed
# One at a time, so that a double click can not start every test twice
running = PipelineRun.objects.filter(pipeline=found, status='RUNNING').first()
if running:
return OpenBench.views.redirect(request, '/pipelines/run/%d/' % (running.id),
error='This pipeline is already running. Cancel that run if you want to start over')
run, issues = OpenBench.pipelines.start_pipeline(found, starter=profile.user.username)
if run is None:
problems = '\n'.join(i['message'] for i in issues if i['level'] == 'error')
return OpenBench.views.redirect(request, '/pipelines/%d/' % (found.id), error='Could not start the pipeline:\n' + problems)
first = StepRun.objects.filter(run=run).order_by('id').first()
if run.status == 'ERROR' and first:
return OpenBench.views.redirect(request, '/pipelines/run/%d/' % (run.id), error='The first test could not be created:\n' + first.message)
return OpenBench.views.redirect(request, '/pipelines/run/%d/' % (run.id), status='Run started')
@require_POST
def pipeline_toggle(request, id):
managed, refusal = _managed(request, id, 'toggle')
if refusal: return refusal
found, profile = managed
found.enabled = not found.enabled
found.save()
_audit(profile.user.username, 'PIPELINE #%d %s' % (found.id, 'RESUMED' if found.enabled else 'PAUSED'))
return OpenBench.views.redirect(request, '/pipelines/%d/' % (found.id), status='Pipeline resumed' if found.enabled else 'Pipeline paused')
@require_POST
def pipeline_delete(request, id):
managed, refusal = _managed(request, id, 'delete')
if refusal: return refusal
found, profile = managed
found.deleted = True
found.save()
for run in PipelineRun.objects.filter(pipeline=found, status='RUNNING'):
OpenBench.pipelines.cancel_run(run.id, profile.user.username)
_audit(profile.user.username, 'PIPELINE #%d DELETED' % (found.id))
return OpenBench.views.redirect(request, '/pipelines/', status='Pipeline deleted')
@require_POST
def pipeline_run_cancel(request, run_id):
profile = viewer(request)
if profile is None:
return _turn_away(request, profile)
run = PipelineRun.objects.select_related('pipeline').filter(id=run_id).first()
if run is None:
return _missing(request)
if not can_manage(profile, run.pipeline):
return _turn_away(request, profile, run.pipeline_id, 'cancel')
if not OpenBench.pipelines.cancel_run(run.id, profile.user.username):
return OpenBench.views.redirect(request, '/pipelines/run/%d/' % (run.id), error='This run is already over')
return OpenBench.views.redirect(request, '/pipelines/run/%d/' % (run.id), status='Run cancelled')
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
# EDITING #
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
# Anybody with an enabled account may make a Pipeline, just like they may make a
# Test. Changing one later is the same can_manage() rule as everything else.
# The editor page builds the graph in the browser. Whatever it sends is never
# trusted: it is validated here by exactly the code that validates a run.
MAX_GRAPH_BYTES = 262144
_GENERAL_DEFAULTS = {
'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',
}
PAYLOAD_DEFAULTS = {
'TEST' : dict(_GENERAL_DEFAULTS, workload_size='32', test_mode='SPRT', test_bounds='[0.00, 3.00]', test_confidence='[0.05, 0.05]'),
'TUNE' : dict(_GENERAL_DEFAULTS),
'DATAGEN' : dict(_GENERAL_DEFAULTS, workload_size='32'),
}
def _blank_graph():
return {
'version' : graphs.SCHEMA_VERSION,
'start' : 'step1',
'max_visits' : graphs.DEFAULT_MAX_VISITS,
'max_steps' : graphs.DEFAULT_MAX_STEPS,
'steps' : { 'step1' : { 'name' : 'Step 1', 'kind' : 'TEST', 'payload' : dict(PAYLOAD_DEFAULTS['TEST']) } },
'edges' : [],
}
def _parse_graph(raw):
if not isinstance(raw, str) or len(raw) > MAX_GRAPH_BYTES:
return None
try: graph = json.loads(raw)
except ValueError: return None
return graph if isinstance(graph, dict) else None
def _tidy(graph):
keys = ('version', 'start', 'max_visits', 'max_steps', 'steps', 'edges')
return { key : graph[key] for key in keys if key in graph }
def _check(graph):
# validate_graph() is built for garbage, but a page that talks to the browser
# should never answer with a 500 because of what the browser sent
try: return graphs.validate_graph(graph)
except Exception: return [graphs.issue('error', 'graph.invalid', 'The pipeline is not valid')]
def _named(issues, graph):
steps = graph.get('steps') if isinstance(graph, dict) else None
steps = steps if isinstance(steps, dict) else {}
named = []
for entry in issues:
step = steps.get(entry['step']) if isinstance(entry['step'], str) else None
name = step.get('name') if isinstance(step, dict) else None
named.append(dict(entry, name=name or entry['step']))
return named
def _editor(request, pipeline, name, graph, issues=None, error=None):
data = {
'pipeline' : pipeline,
'name' : name,
'graph' : graph,
'issues' : _named(issues or [], graph),
'meta' : {
'kinds' : list(graphs.KINDS),
'outcomes' : list(graphs.EDGE_CONDITIONS),
'required' : graphs.REQUIRED_FIELDS,
'conditional' : graphs.CONDITIONAL_FIELDS,
'allowed' : sorted(graphs.ALLOWED_FIELDS),
'defaults' : PAYLOAD_DEFAULTS,
'limits' : { 'steps' : graphs.LIMIT_STEPS, 'visits' : graphs.LIMIT_MAX_VISITS, 'total' : graphs.LIMIT_MAX_STEPS },
},
}
return OpenBench.views.render(request, 'pipeline_edit.html', data, error=error)
def _submit(request, profile, found):
""" Shared by creating and editing. Saves, or shows the editor again with what was wrong """
name = (request.POST.get('name') or '').strip()
graph = _parse_graph(request.POST.get('graph'))
errors = []
if not (1 <= len(name) <= 128):
errors.append('Give the pipeline a name of up to 128 characters')
if graph is None:
errors.append('The pipeline could not be read. Reload the page and try again')
return _editor(request, found, name, _blank_graph(), error='\n'.join(errors))
issues = _check(graph)
if graphs.has_errors(issues):
errors.append('The pipeline has problems, see the checks below')
if errors:
return _editor(request, found, name, graph, issues, error='\n'.join(errors))
graph = _tidy(graph)
if found is None:
found = Pipeline.objects.create(name=name, author=profile.user.username, graph=graph)
action = 'CREATED'
else:
found.name = name
found.graph = graph
found.save()
action = 'EDITED'
_audit(profile.user.username, 'PIPELINE #%d %s' % (found.id, action))
return OpenBench.views.redirect(request, '/pipelines/%d/' % (found.id), status='Pipeline saved')
def pipeline_new(request):
profile = viewer(request)
if profile is None:
return _turn_away(request, profile)
if request.method != 'POST':
return _editor(request, None, '', _blank_graph())
return _submit(request, profile, None)
def pipeline_edit(request, id):
profile = viewer(request)
if profile is None:
return _turn_away(request, profile)
found = Pipeline.objects.filter(id=id, deleted=False).first()
if found is None:
return _missing(request)
if not can_manage(profile, found):
return _turn_away(request, profile, id, 'edit')
# Runs that are going work from a snapshot of the graph, so this is safe at any time
if request.method != 'POST':
return _editor(request, found, found.name, copy.deepcopy(found.graph))
return _submit(request, profile, found)
@require_POST
def pipeline_check(request):
""" Validates a graph without saving it, for the Check button of the editor """
if viewer(request) is None:
return JsonResponse({ 'error' : 'Not allowed' }, status=403)
graph = _parse_graph(request.POST.get('graph'))
if graph is None:
return JsonResponse({ 'issues' : [graphs.issue('error', 'graph.invalid', 'The pipeline could not be read')] })
return JsonResponse({ 'issues' : _check(graph) })
MAX_PREVIEW_EDGES = 400
def _drawable(graph):
""" Whether a graph is sound enough in shape to be laid out. Whatever else is
wrong with it, the editor still wants to see it, so that it can be fixed """
steps, edges = graph.get('steps'), graph.get('edges', [])
return (
isinstance(steps, dict) and 0 < len(steps) <= graphs.LIMIT_STEPS
and all(isinstance(step, dict) for step in steps.values())
and isinstance(edges, list) and len(edges) <= MAX_PREVIEW_EDGES
and all(isinstance(edge, dict) for edge in edges)
)
@require_POST
def pipeline_preview(request):
""" The flow of a graph as it is drawn on a run, and its checks, for the
editor to show while a pipeline is being built. Saves nothing """
if viewer(request) is None:
return JsonResponse({ 'error' : 'Not allowed' }, status=403)
graph = _parse_graph(request.POST.get('graph'))
if graph is None:
return JsonResponse({ 'svg' : '', 'issues' : [graphs.issue('error', 'graph.invalid', 'The pipeline could not be read')] })
svg = ''
if _drawable(graph):
try: svg = drawing.render_svg(graph)
except Exception: svg = '' # A half built graph is not a reason for a 500
return JsonResponse({ 'svg' : svg, 'issues' : _named(_check(graph), graph) })
def pipeline_test_fields(request, test_id):
""" The settings of an existing SPRT or Games test, as the settings of a step """
if viewer(request) is None:
return JsonResponse({ 'error' : 'Not allowed' }, status=403)
test = Test.objects.select_related('dev', 'base').filter(id=test_id).first()
if test is None or test.test_mode not in ('SPRT', 'GAMES'):
return JsonResponse({ 'error' : 'There is no SPRT or Games test with that number' }, status=404)
fields = {
'dev_engine' : test.dev_engine, 'base_engine' : test.base_engine,
'dev_repo' : test.dev_repo, 'base_repo' : test.base_repo,
'dev_branch' : test.dev.name, 'base_branch' : test.base.name,
'dev_network' : test.dev_network, 'base_network' : test.base_network,
'dev_options' : test.dev_options, 'base_options' : test.base_options,
'dev_time_control' : test.dev_time_control, 'base_time_control' : test.base_time_control,
'book_name' : test.book_name, 'upload_pgns' : test.upload_pgns,
'priority' : test.priority, 'throughput' : test.throughput,
'workload_size' : test.workload_size, 'test_mode' : test.test_mode,
'syzygy_wdl' : test.syzygy_wdl, 'syzygy_adj' : test.syzygy_adj,
'win_adj' : test.win_adj, 'draw_adj' : test.draw_adj,
}
if test.test_mode == 'SPRT':
fields['test_bounds'] = '[%.2f, %.2f]' % (test.elolower, test.eloupper)
fields['test_confidence'] = '[%.2f, %.2f]' % (test.beta, test.alpha)
else:
fields['test_max_games'] = test.max_games
return JsonResponse({ 'payload' : { key : str(value) for key, value in fields.items() } })
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
# QUICK START #
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
# What the New pipeline button opens. It asks for one thing, the dev branch, and
# fills in everything else the way that the Create Test page does ( the same
# presets, the same defaults, see pipeline_defaults.py ), so that a branch and an
# Enter are all that it takes, as they are for a single test. What comes out is a
# plain pipeline, which the editor can change like any other.
def _quick_engine(profile, wanted):
""" The engine to make tests for: the one asked for, else the default of this
person, else the first there is. '' when the server has none at all """
engines = OpenBench.config.OPENBENCH_CONFIG['engines']
for name in (wanted, profile.engine):
if name in engines:
return name
return next(iter(engines), '')
def _quick_choices(engine_config):
""" ( the presets to choose from, the one that goes first, the one that follows ) """
names = defaults.preset_names(engine_config)
first = 'STC' if 'STC' in names else (names[0] if names else '')
then = 'LTC' if 'LTC' in names and first != 'LTC' else ''
choices = [{ 'name' : name, 'time' : defaults.time_control(engine_config, name) } for name in names]
return choices, first, then
def _quick_page(request, engine, choices, form, error=None):
config = OpenBench.config.OPENBENCH_CONFIG
# What the presets say about the base branch, to show where the box is left blank
base = defaults.test_payload(engine, config['engines'][engine], form['first'], 'dev')[0].get('base_branch', '')
data = {
'engine' : engine,
'engines' : list(config['engines']),
'choices' : choices,
'form' : form,
'base' : base,
'more' : bool(form['base_branch'] or form['name'] or not base),
}
return OpenBench.views.render(request, 'pipeline_quick.html', data, error=error)
def pipeline_quick(request):
profile = viewer(request)
if profile is None:
return _turn_away(request, profile)
config = OpenBench.config.OPENBENCH_CONFIG
source = request.POST if request.method == 'POST' else request.GET
engine = _quick_engine(profile, source.get('engine'))
if not engine:
return OpenBench.views.redirect(request, '/pipelines/', error='No engine is set up on this server')
engine_config = config['engines'][engine]
choices, first, then = _quick_choices(engine_config)
names = [choice['name'] for choice in choices]
if not names:
return OpenBench.views.redirect(request, '/pipelines/new/', error='%s has no test presets, so its pipelines are made here' % (engine))
asked = {
'dev_branch' : (source.get('dev_branch' ) or '').strip(),
'base_branch' : (source.get('base_branch') or '').strip(),
'name' : (source.get('name' ) or '').strip(),
'first' : source.get('first', first),
'then' : source.get('then' , then ),
}
form = dict(asked,
first = asked['first'] if asked['first'] in names else first,
then = asked['then' ] if asked['then' ] in names else '')
if request.method != 'POST':
return _quick_page(request, engine, choices, form)
errors = []
branch = defaults.clean_branch(asked['dev_branch'])
if not asked['dev_branch']:
errors.append('Type the name of the branch to test')
elif branch is None:
errors.append('"%s" cannot be a branch, which has no spaces or quotes' % (asked['dev_branch'][:40]))
base = asked['base_branch']
if base and defaults.clean_branch(base) is None:
errors.append('"%s" cannot be a branch, which has no spaces or quotes' % (base[:40]))
if asked['first'] not in names:
errors.append('Pick the test to run first')
if asked['then'] and asked['then'] not in names:
errors.append('Pick the test to run after it, or none')
if errors:
return _quick_page(request, engine, choices, form, error='\n'.join(errors))
networks = list(Network.objects.all().values())
books = list(config['books'])
plan = [asked['first']] + ([asked['then']] if asked['then'] else [])
steps, lacking = [], []
for preset in plan:
payload, absent = defaults.test_payload(engine, engine_config, preset, branch, profile.repos, networks, books, base)
steps.append((preset, payload))
lacking += [(preset, key) for key in absent]
if any(key == 'base_branch' for _, key in lacking):
errors.append('Type the base branch, as the engine does not say which one to test against')
others = ['%s (%s)' % (key.replace('_', ' '), preset) for preset, key in lacking if key != 'base_branch']
if others:
errors.append('The presets of %s leave out: %s\nFill those in with the editor' % (engine, ', '.join(others)))
if errors:
return _quick_page(request, engine, choices, form, error='\n'.join(errors))
graph = defaults.quick_graph(steps)
issues = _check(graph)
if graphs.has_errors(issues): # Nothing for a person to fix: this page never builds anything that is wrong
problems = '\n'.join(i['message'] for i in issues if i['level'] == 'error')
return _quick_page(request, engine, choices, form, error='The pipeline could not be made:\n' + problems)
author = profile.user.username
title = asked['name'][:128] or defaults.quick_name(branch, [label for label, _ in steps])
pipeline = Pipeline.objects.create(name=title, author=author, graph=_tidy(graph))
pipeline_id = pipeline.id
_audit(author, 'PIPELINE #%d CREATED' % (pipeline_id))
if request.POST.get('action') == 'save':
return OpenBench.views.redirect(request, '/pipelines/%d/' % (pipeline_id), status='Pipeline saved')
run, issues = OpenBench.pipelines.start_pipeline(pipeline, starter=author)
first_step = StepRun.objects.filter(run=run).order_by('id').first() if run else None
if run is None or (run.status == 'ERROR' and first_step):
reason = first_step.message if first_step else '\n'.join(i['message'] for i in issues if i['level'] == 'error')
# Nothing was made, and a pipeline that never made anything is of no use to anybody
pipeline.delete()
_audit(author, 'PIPELINE #%d DISCARDED' % (pipeline_id))
return _quick_page(request, engine, choices, form, error='The first test could not be created:\n' + reason)
return OpenBench.views.redirect(request, '/pipelines/run/%d/' % (run.id), status='Pipeline started')
+88
View File
@@ -0,0 +1,88 @@
/* ==========================================================================
OpenBench - Pipeline run page
Keeps a run up to date while it is going. The server draws the page, so this
only asks for the page again, and swaps in the part that changed. It stops
once the run is over, and does nothing while the tab is hidden.
========================================================================== */
(function () {
'use strict';
var live = document.getElementById('pl-live');
if (!live || live.dataset.running !== 'true')
return;
var STAMP = {
year : 'numeric', month : '2-digit', day : '2-digit',
hour : '2-digit', minute : '2-digit', second : '2-digit', hour12 : false,
};
var timer = null;
var busy = false;
// Same formatting that the base template applies when the page loads
function stamp(root) {
var nodes = root.getElementsByClassName('timestamp');
for (var i = 0; i < nodes.length; i++) {
var seconds = Number(nodes[i].textContent);
if (isFinite(seconds) && seconds > 0)
nodes[i].textContent = new Date(1000 * seconds).toLocaleString(undefined, STAMP);
}
}
function stop() {
clearInterval(timer);
document.removeEventListener('visibilitychange', onVisible);
}
function onVisible() {
if (!document.hidden)
refresh();
}
function refresh() {
if (busy || document.hidden)
return;
busy = true;
fetch(window.location.href, { credentials : 'same-origin', headers : { 'Accept' : 'text/html' } })
.then(function (response) {
if (!response.ok) throw new Error('HTTP ' + response.status);
return response.text();
})
.then(function (html) {
var next = new DOMParser().parseFromString(html, 'text/html').getElementById('pl-live');
if (!next)
return; // Logged out, or the page is gone. Leave what is shown alone
if (next.dataset.signature !== live.dataset.signature) {
stamp(next);
live.replaceWith(next);
live = next;
}
if (live.dataset.running !== 'true')
stop();
})
.catch(function () { /* Try again on the next tick */ })
.then(function () { busy = false; });
}
timer = setInterval(refresh, 5000);
document.addEventListener('visibilitychange', onVisible);
})();
+206
View File
@@ -736,6 +736,212 @@ button.ev-move:hover {
font-size: 12.5px;
}
/* ---------- Pipelines ---------- */
.pl-scroll {
padding: 14px 12px 12px;
overflow-x: auto;
}
.pl-graph {
display: block;
max-width: none;
font-family: var(--font-sans);
}
/* Steps. A step that has not run is quiet, one that has takes on the colour of how it ended */
.pl-box {
fill: var(--color3);
stroke: var(--line-strong);
stroke-width: 1;
}
.pl-name {
fill: var(--color-font1);
font-size: 13.5px;
font-weight: 600;
}
.pl-what,
.pl-speed {
fill: var(--muted);
font-family: var(--font-mono);
font-size: 12px;
}
.pl-status {
fill: var(--muted);
font-size: 11.5px;
font-weight: 600;
}
.pl-play {
fill: var(--accent);
}
.pl-s-queued .pl-box,
.pl-s-launching .pl-box {
stroke: #566074;
stroke-dasharray: 4 3;
}
.pl-s-running .pl-box { fill: var(--accent-soft); stroke: var(--accent); stroke-width: 1.6; }
.pl-s-passed .pl-box { fill: rgba(52, 211, 153, 0.08); stroke: var(--ok); }
.pl-s-failed .pl-box { fill: rgba(248, 113, 113, 0.09); stroke: var(--bad); }
.pl-s-stopped .pl-box { fill: rgba(245, 185, 65, 0.08); stroke: var(--warn); }
.pl-s-error .pl-box { fill: rgba(248, 113, 113, 0.09); stroke: var(--bad); stroke-dasharray: 4 3; }
.pl-s-running .pl-status { fill: var(--accent-hover); }
.pl-s-passed .pl-status { fill: var(--ok); }
.pl-s-failed .pl-status,
.pl-s-error .pl-status { fill: var(--bad); }
.pl-s-stopped .pl-status { fill: var(--warn); }
.pl-unreachable {
opacity: 0.5;
}
.pl-unreachable .pl-box {
stroke-dasharray: 4 3;
}
.pl-graph a {
outline: none;
}
.pl-graph a:hover .pl-box {
stroke-width: 2;
}
.pl-graph a:focus-visible .pl-box {
stroke: var(--accent-hover);
stroke-width: 2.5;
}
/* Edges. The colour says what has to happen for the edge to be followed */
.pl-edge .pl-line {
fill: none;
stroke: #566074;
stroke-width: 1.6;
}
.pl-arrow { fill: #566074; }
.pl-end { fill: #566074; }
.pl-c-passed .pl-line { stroke: var(--ok); }
.pl-c-failed .pl-line { stroke: var(--bad); }
.pl-c-stopped .pl-line { stroke: var(--warn); }
.pl-arrow.pl-c-passed { fill: var(--ok); }
.pl-arrow.pl-c-failed { fill: var(--bad); }
.pl-arrow.pl-c-stopped { fill: var(--warn); }
.pl-back .pl-line {
stroke-dasharray: 5 4;
}
/* On a run, the way that was gone along stands out and the rest steps back */
.pl-taken .pl-line {
stroke-width: 3;
}
.pl-idle .pl-line { opacity: 0.22; }
.pl-idle .pl-label { opacity: 0.45; }
.pl-label rect {
fill: var(--color1);
stroke: var(--line-strong);
}
.pl-label text {
fill: var(--color-font2);
font-size: 11.5px;
font-weight: 500;
}
@media (prefers-reduced-motion: no-preference) {
/* The one thing that moves: the step that is going right now */
@keyframes pl-pulse {
50% { stroke-opacity: 0.4; }
}
.pl-s-running .pl-box {
animation: pl-pulse 2.4s ease-in-out infinite;
}
}
/* Around the graph */
.page-actions form,
.pl-toolbar form {
margin: 0;
}
.pl-toolbar {
display: flex;
align-items: center;
justify-content: space-between;
gap: 12px;
min-height: 38px;
margin-bottom: 16px;
}
.pl-checks {
margin: 0;
padding: 6px 0;
list-style: none;
}
.pl-check {
display: flex;
align-items: flex-start;
gap: 12px;
padding: 9px 16px;
color: var(--color-font2);
}
.pl-check i {
margin-top: 4px;
}
.pl-check strong {
color: var(--color-font1);
}
.pl-check-error i { color: var(--bad); }
.pl-check-warning i { color: var(--warn); }
.pl-check-info i { color: var(--accent); }
#content td.pl-leads {
white-space: normal;
}
#content .pl-message {
max-width: 52ch;
white-space: pre-wrap;
word-break: break-word;
}
/* On the page of a test that a pipeline started */
.pl-chip {
display: inline-flex;
align-items: center;
gap: 8px;
margin-bottom: 14px;
padding: 6px 12px;
background-color: var(--accent-soft);
border: 1px solid rgba(76, 141, 255, 0.4);
border-radius: var(--radius);
color: var(--color-font1);
font-size: 13px;
}
/* ---------- Responsive ---------- */
@media (max-width: 767px) {
File diff suppressed because it is too large. Load diff
+16 -1
View File
@@ -18,7 +18,7 @@
# #
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
import django.urls, OpenBench.views, OpenBench.seo
import django.urls, OpenBench.views, OpenBench.pipeline_views, OpenBench.seo
urlpatterns = [
@@ -42,6 +42,21 @@ urlpatterns = [
django.urls.path(r'greens/<int:page>/', OpenBench.views.greens),
django.urls.path(r'search/', OpenBench.views.search),
# Links for viewing and managing Pipelines
django.urls.path(r'pipelines/', OpenBench.pipeline_views.pipelines),
django.urls.path(r'pipelines/<int:id>/', OpenBench.pipeline_views.pipeline),
django.urls.path(r'pipelines/<int:id>/start/', OpenBench.pipeline_views.pipeline_start),
django.urls.path(r'pipelines/<int:id>/toggle/', OpenBench.pipeline_views.pipeline_toggle),
django.urls.path(r'pipelines/<int:id>/delete/', OpenBench.pipeline_views.pipeline_delete),
django.urls.path(r'pipelines/<int:id>/edit/', OpenBench.pipeline_views.pipeline_edit),
django.urls.path(r'pipelines/new/', OpenBench.pipeline_views.pipeline_new),
django.urls.path(r'pipelines/quick/', OpenBench.pipeline_views.pipeline_quick),
django.urls.path(r'pipelines/check/', OpenBench.pipeline_views.pipeline_check),
django.urls.path(r'pipelines/preview/', OpenBench.pipeline_views.pipeline_preview),
django.urls.path(r'pipelines/test-fields/<int:test_id>/', OpenBench.pipeline_views.pipeline_test_fields),
django.urls.path(r'pipelines/run/<int:run_id>/', OpenBench.pipeline_views.pipeline_run),
django.urls.path(r'pipelines/run/<int:run_id>/cancel/', OpenBench.pipeline_views.pipeline_run_cancel),
# Links for viewing general information tables
django.urls.path(r'users/', OpenBench.views.users),
django.urls.path(r'event/<int:id>/', OpenBench.views.event),
+1
View File
@@ -158,6 +158,7 @@
<li><a href="/index"><i class="fa-solid fa-house fa-fw"></i> Index</a></li>
<li><a href="/greens"><i class="fa-solid fa-heart fa-fw"></i> Greens</a></li>
<li><a href="/search"><i class="fa-solid fa-magnifying-glass fa-fw"></i> Search</a></li>
<li><a href="/pipelines"><i class="fa-solid fa-diagram-project fa-fw"></i> Pipelines</a></li>
</ul>
</div>
+143
View File
@@ -0,0 +1,143 @@
{% extends "OpenBench/base.html" %}
{% block page_head %}
<div>
<a class="crumb" href="/pipelines/"><i class="fa-solid fa-chevron-left"></i> Pipelines</a>
<h1 class="page-title">{{ pipeline.name }}</h1>
<p class="page-sub">By {{ pipeline.author|capfirst }}</p>
</div>
<div class="page-actions">
{% if not pipeline.enabled %}<span class="badge badge-warn">Paused</span>{% endif %}
{% if can_manage %}
{% if running %}
<a class="anchorbutton btn-start" href="/pipelines/run/{{ running.id }}/">Open the running run</a>
{% elif pipeline.enabled and usable %}
<form method="post" action="/pipelines/{{ pipeline.id }}/start/">
{% csrf_token %}
<button class="anchorbutton btn-blue" type="submit">Start run</button>
</form>
{% else %}
<button class="anchorbutton btn-disabled" type="button" disabled
title="{% if usable %}Resume the pipeline to start it{% else %}Fix the pipeline settings first{% endif %}">Start run</button>
{% endif %}
<a class="anchorbutton btn-start" href="/pipelines/{{ pipeline.id }}/edit/">Edit</a>
<form method="post" action="/pipelines/{{ pipeline.id }}/toggle/">
{% csrf_token %}
<button class="anchorbutton btn-start" type="submit">{% if pipeline.enabled %}Pause{% else %}Resume{% endif %}</button>
</form>
<form method="post" action="/pipelines/{{ pipeline.id }}/delete/"
onsubmit="return confirm('Delete this pipeline? Runs that are going are cancelled. Tests that already started keep running.');">
{% csrf_token %}
<button class="anchorbutton btn-red" type="submit">Delete</button>
</form>
{% endif %}
</div>
{% endblock %}
{% block content %}
{% if usable %}
<div class="card">
<div class="card-head"><h2 class="card-title">Flow</h2></div>
<div class="pl-scroll">{{ svg|safe }}</div>
</div>
{% else %}
<div class="banner error-message" role="alert">
<i class="fa-solid fa-circle-exclamation banner-icon"></i>
<pre>This pipeline cannot run because its settings are damaged. Use Edit to fix them.</pre>
</div>
{% endif %}
{% if issues %}
<div class="card">
<div class="card-head">
<h2 class="card-title">Checks</h2>
<span class="count">{{ issues|length }}</span>
</div>
<ul class="pl-checks">
{% for issue in issues %}
<li class="pl-check pl-check-{{ issue.level }}">
<i class="fa-solid {% if issue.level == 'error' %}fa-circle-exclamation{% elif issue.level == 'warning' %}fa-triangle-exclamation{% else %}fa-circle-info{% endif %}"></i>
<span>{% if issue.name %}<strong>{{ issue.name }}</strong> {% endif %}{{ issue.message }}</span>
</li>
{% endfor %}
</ul>
</div>
{% endif %}
{% if steps %}
<div class="card">
<div class="card-head">
<h2 class="card-title">Steps</h2>
<span class="count">{{ steps|length }}</span>
</div>
<table class="stripes">
<tr class="table-header">
<th>Step</th>
<th>Kind</th>
<th>Runs</th>
<th>What happens next</th>
</tr>
{% for step in steps %}
<tr>
<td class="col-test">{{ step.name }}{% if step.start %} <span class="badge badge-info">Starts here</span>{% endif %}</td>
<td>{{ step.kind }}</td>
<td class="col-tc">{{ step.what }} {{ step.speed }}</td>
<td class="pl-leads">
{% for line in step.leads %}<div>{{ line }}</div>{% empty %}<span class="muted">The pipeline ends here</span>{% endfor %}
</td>
</tr>
{% endfor %}
</table>
</div>
{% endif %}
<div class="card">
<div class="card-head">
<h2 class="card-title">Runs</h2>
<span class="count">{{ runs|length }}</span>
</div>
{% if runs %}
<table class="hoverable">
<tr class="table-header">
<th>Run</th>
<th>Started</th>
<th>By</th>
<th>Status</th>
</tr>
{% for run in runs %}
<tr data-href="/pipelines/run/{{ run.id }}/">
<td class="col-test"><a href="/pipelines/run/{{ run.id }}/">Run {{ run.id }}</a></td>
<td class="col-date"><span class="timestamp">{{ run.started|date:"U" }}</span></td>
<td>{{ run.starter|capfirst }}</td>
<td><span class="badge {{ run.state.badge }}">{{ run.state.label }}</span></td>
</tr>
{% endfor %}
</table>
{% else %}
<div class="empty-state">
<i class="fa-solid fa-flag-checkered"></i>
<p>This pipeline has not run yet.</p>
{% if can_manage and pipeline.enabled and usable %}<p class="muted-small">Use Start run to begin with the first step.</p>{% endif %}
</div>
{% endif %}
</div>
{% endblock %}
+892
View File
@@ -0,0 +1,892 @@
{% extends "OpenBench/base.html" %}
{% block page_head %}
<div>
<a class="crumb" href="{% if pipeline %}/pipelines/{{ pipeline.id }}/{% else %}/pipelines/{% endif %}"><i class="fa-solid fa-chevron-left"></i> {% if pipeline %}{{ pipeline.name }}{% else %}Pipelines{% endif %}</a>
<h1 class="page-title">{% if pipeline %}Edit pipeline{% else %}New pipeline{% endif %}</h1>
<p class="page-sub">Draw what runs, and what starts when it ends</p>
</div>
{% endblock %}
{% block content %}
<style>
.ed input, .ed select, .ed textarea { font: inherit; color: inherit; background: transparent; border: 1px solid var(--line-strong, rgba(128, 128, 128, .4)); border-radius: var(--radius, 4px); padding: .35rem .5rem; box-sizing: border-box; }
.ed select option { background: var(--color2, #1c2230); color: var(--color-font1, inherit); }
.ed textarea { resize: vertical; width: 100%; }
.ed label { display: block; font-size: .8rem; opacity: .75; margin-bottom: .2rem; }
.ed summary { cursor: pointer; }
.ed-small { font-size: .85rem; padding: .25rem .6rem; }
.ed-pad { padding: 0 .9rem .9rem; }
.ed-note { font-size: .85rem; opacity: .8; margin: .3rem 0; }
.ed-h { margin: 1rem 0 .4rem; font-size: .9rem; }
.ed-inline { display: flex; flex-wrap: wrap; gap: .45rem; align-items: center; }
.ed-top { display: flex; flex-wrap: wrap; gap: .75rem 1.25rem; align-items: flex-end; padding: .9rem; }
.ed-title { flex: 1 1 18rem; }
.ed-title input { width: 100%; }
.ed-work { display: grid; grid-template-columns: minmax(0, 1fr) 25rem; gap: 1rem; align-items: start; margin-bottom: 1rem; }
@media (max-width: 70rem) { .ed-work { grid-template-columns: minmax(0, 1fr); } }
.ed-canvas { position: relative; overflow: auto; padding: 14px 12px 12px; min-height: 12rem; }
.ed-canvas svg { display: block; max-width: none; }
.ed-hint { margin: 0; padding: 0 .9rem .8rem; font-size: .85rem; color: var(--muted, inherit); }
.ed-hint-warn { color: var(--warn, #f5b941); }
.ed-canvas g.pl-node, .ed-canvas g.pl-edge { cursor: pointer; }
.ed-canvas g.pl-node:hover .pl-box { stroke-width: 2; }
.ed-canvas g.pl-edge:hover .pl-line { stroke-width: 2.6; }
.ed-canvas g.pl-node.ed-sel .pl-box { stroke: var(--accent-hover, #6ea2ff); stroke-width: 2.6; fill: var(--accent-soft, rgba(76, 141, 255, .15)); }
.ed-canvas g.pl-edge.ed-sel .pl-line { stroke-width: 3.4; }
.ed-canvas g.pl-edge.ed-sel .pl-label rect { stroke: var(--accent-hover, #6ea2ff); }
.ed-canvas g.pl-node.ed-bad .pl-box { stroke: var(--bad, #f87171); stroke-dasharray: 5 3; }
.ed-canvas g.pl-node.ed-warn .pl-box { stroke: var(--warn, #f5b941); stroke-dasharray: 5 3; }
.ed-canvas .ed-hit { fill: none; stroke: transparent; stroke-width: 16; pointer-events: stroke; }
.ed-plus { cursor: pointer; }
.ed-plus circle { fill: var(--color2, #1c2230); stroke: var(--accent, #4c8dff); stroke-width: 1.5; }
.ed-plus path { fill: none; stroke: var(--accent-hover, #6ea2ff); stroke-width: 1.8; stroke-linecap: round; }
.ed-plus:hover circle { fill: var(--accent, #4c8dff); }
.ed-plus:hover path { stroke: #fff; }
.ed-menu { position: absolute; z-index: 6; width: 12rem; padding: .3rem; background: var(--color2, #1c2230); border: 1px solid var(--line-strong, rgba(128, 128, 128, .4)); border-radius: var(--radius, 4px); box-shadow: 0 6px 20px rgba(0, 0, 0, .35); }
.ed-menu[hidden] { display: none; }
.ed-menu-title { padding: .25rem .5rem; font-size: .75rem; color: var(--muted, inherit); }
.ed-menu-item { display: flex; align-items: center; gap: .55rem; width: 100%; padding: .4rem .5rem; background: none; border: 0; border-radius: var(--radius, 4px); color: var(--color-font1, inherit); font: inherit; text-align: left; cursor: pointer; }
.ed-menu-item:hover { background: var(--surface-hover, rgba(128, 128, 128, .15)); }
.ed-menu-item small { margin-left: auto; color: var(--muted, inherit); }
.ed-menu-passed i { color: var(--ok, #34d399); }
.ed-menu-failed i { color: var(--bad, #f87171); }
.ed-menu-stopped i { color: var(--warn, #f5b941); }
.ed-menu-any i { color: var(--muted, inherit); }
.ed-panel { position: sticky; top: 1rem; max-height: calc(100vh - 2rem); overflow: auto; }
.ed-tag { padding: .1rem .55rem; border-radius: 999px; font-size: .75rem; background: var(--accent-soft, rgba(76, 141, 255, .15)); color: var(--accent-hover, inherit); }
.ed-box { border: 1px solid var(--line, rgba(128, 128, 128, .3)); border-radius: 8px; padding: .7rem; margin: 0 0 .6rem; }
.ed-picked { border-color: var(--accent-hover, #6ea2ff); box-shadow: inset 2px 0 0 var(--accent, #4c8dff); }
.ed-rule details { margin-top: .5rem; font-size: .85rem; }
.ed-group { margin-top: .8rem; }
.ed-group > summary { font-weight: 600; font-size: .85rem; }
.ed-grid { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: .5rem .6rem; margin-top: .5rem; }
.ed-field input, .ed-field select { width: 100%; }
.ed-wide { grid-column: 1 / -1; }
.ed-empty { border-color: var(--bad, #d9534f) !important; }
.ed-set-row { display: grid; grid-template-columns: 7rem minmax(0, 1fr) auto; gap: .4rem; align-items: center; margin: .4rem 0; }
.ed-set-row label { margin: 0; }
.ed-jump { cursor: pointer; }
.ed-jump:hover { background: var(--surface-hover, rgba(128, 128, 128, .12)); }
.pl-check-ok i { color: var(--ok, #34d399); }
.ed-limits { padding: .9rem; }
.ed-actions { display: flex; gap: .75rem; align-items: center; margin: 1rem 0; }
</style>
<form id="pl-form" class="ed" method="post" autocomplete="off">
{% csrf_token %}
<input type="hidden" name="graph" id="pl-graph" value="">
<div class="card">
<div class="ed-top">
<div class="ed-title">
<label for="pl-name">Name</label>
<input id="pl-name" name="name" value="{{ name }}" maxlength="128" required placeholder="For example: STC, then LTC if it passes">
</div>
<div>
<label>Add a step that is not connected yet</label>
<div class="ed-inline">
<button type="button" id="pl-add-test" class="anchorbutton btn-blue ed-small"><i class="fa-solid fa-plus"></i> Test</button>
<button type="button" id="pl-add-tune" class="anchorbutton btn-blue ed-small"><i class="fa-solid fa-plus"></i> Tune</button>
<button type="button" id="pl-add-datagen" class="anchorbutton btn-blue ed-small"><i class="fa-solid fa-plus"></i> Datagen</button>
</div>
</div>
</div>
</div>
<div class="ed-work">
<div class="card">
<div class="card-head"><h2 class="card-title">Flow</h2></div>
<div class="ed-canvas" id="pl-canvas">
<div id="pl-stage"></div>
<div class="ed-menu" id="pl-menu" role="menu" hidden></div>
</div>
<p class="ed-hint" id="pl-hint"></p>
</div>
<div class="card ed-panel" id="pl-panel"></div>
</div>
<div class="card">
<div class="card-head"><h2 class="card-title">Checks</h2></div>
<ul class="pl-checks" id="pl-checks">
{% for issue in issues %}
<li class="pl-check pl-check-{{ issue.level }}">
<i class="fa-solid {% if issue.level == 'error' %}fa-circle-exclamation{% elif issue.level == 'warning' %}fa-triangle-exclamation{% else %}fa-circle-info{% endif %}"></i>
<span>{% if issue.name %}<strong>{{ issue.name }}</strong> {% endif %}{{ issue.message }}</span>
</li>
{% endfor %}
</ul>
</div>
<div class="card">
<details class="ed-limits">
<summary>Limits, so that a loop can never run forever</summary>
<div class="ed-inline" style="margin-top: .7rem; gap: .75rem 1.25rem">
<div>
<label for="pl-visits">Most runs of one step</label>
<input id="pl-visits" type="number" min="1" style="width: 7rem">
</div>
<div>
<label for="pl-total">Most tests in one run</label>
<input id="pl-total" type="number" min="1" style="width: 7rem">
</div>
</div>
</details>
</div>
<div class="ed-actions">
<button type="submit" class="anchorbutton btn-blue">Save pipeline</button>
<a href="{% if pipeline %}/pipelines/{{ pipeline.id }}/{% else %}/pipelines/{% endif %}">Cancel</a>
</div>
</form>
{{ graph|json_script:"graph-data" }}
{{ meta|json_script:"meta-data" }}
<script>
(function () {
'use strict';
const NS = 'http://www.w3.org/2000/svg';
const meta = JSON.parse(document.getElementById('meta-data').textContent);
const seed = JSON.parse(document.getElementById('graph-data').textContent);
const form = document.getElementById('pl-form');
const token = form.querySelector('input[name=csrfmiddlewaretoken]').value;
const stage = document.getElementById('pl-stage');
const menu = document.getElementById('pl-menu');
const panel = document.getElementById('pl-panel');
const hint = document.getElementById('pl-hint');
const checks = document.getElementById('pl-checks');
const isObj = value => value !== null && typeof value === 'object' && !Array.isArray(value);
const root = isObj(seed) ? seed : {};
const texts = obj => {
const out = {};
if (isObj(obj)) Object.keys(obj).forEach(key => { out[key] = String(obj[key]); });
return out;
};
// Words
const OUTCOME_TEXT = { passed : 'it passes', failed : 'it fails', stopped : 'it is stopped', any : 'it ends, however it ends' };
const MENU_TEXT = { passed : 'If it passes', failed : 'If it fails', stopped : 'If it is stopped', any : 'However it ends' };
const MENU_ICON = { passed : 'fa-check', failed : 'fa-xmark', stopped : 'fa-stop', any : 'fa-arrows-rotate' };
const KIND_LABEL = { TEST : 'Test (SPRT or fixed games)', TUNE : 'Tune (SPSA)', DATAGEN : 'Datagen' };
const IMPOSSIBLE = { TUNE : ['failed'], DATAGEN : ['failed'] }; // A finished tune or datagen always passes
const OPTIONAL = ['dev_bench', 'base_bench'];
const LABEL = {
engine : 'Engine', repo : 'Repository', branch : 'Branch', network : 'Network', options : 'UCI options',
time_control : 'Time control', bench : 'Bench',
book_name : 'Opening book', upload_pgns : 'Upload PGNs', priority : 'Priority', throughput : 'Throughput',
syzygy_wdl : 'Syzygy WDL', syzygy_adj : 'Syzygy adjudication', win_adj : 'Win adjudication', draw_adj : 'Draw adjudication',
workload_size : 'Games per workload', test_mode : 'Mode', test_bounds : 'SPRT bounds',
test_confidence : 'SPRT confidence', test_max_games : 'Number of games',
spsa_alpha : 'Alpha', spsa_gamma : 'Gamma', spsa_A_ratio : 'A ratio', spsa_iterations : 'Iterations',
spsa_pairs_per : 'Pairs per iteration', spsa_reporting_type : 'Reporting', spsa_distribution_type : 'Distribution',
spsa_inputs : 'Parameters',
datagen_max_games : 'Games', datagen_custom_genfens : 'Custom genfens', datagen_play_reverses : 'Play reverses',
};
function label(key) {
const side = key.startsWith('dev_') ? 'dev_' : key.startsWith('base_') ? 'base_' : '';
return LABEL[key] || LABEL[key.slice(side.length)] || key;
}
function fullLabel(key) {
const side = key.startsWith('dev_') ? 'Dev ' : key.startsWith('base_') ? 'Base ' : '';
return side + label(key).toLowerCase();
}
const GROUP_ORDER = ['Match', 'Dev', 'Base', 'SPSA', 'Datagen', 'Advanced'];
const GROUP_TITLE = {
Match : 'Games', Dev : 'Dev (the change)', Base : 'Base (what it is compared with)',
SPSA : 'SPSA', Datagen : 'Datagen', Advanced : 'Advanced',
};
function groupOf(key) {
if (key.startsWith('dev_')) return 'Dev';
if (key.startsWith('base_')) return 'Base';
if (key.startsWith('spsa_')) return 'SPSA';
if (key.startsWith('datagen_')) return 'Datagen';
if (key.startsWith('test_') || key === 'book_name' || key === 'workload_size') return 'Match';
return 'Advanced';
}
const CHOICES = { test_mode : ['SPRT', 'GAMES'], upload_pgns : ['FALSE', 'TRUE'] };
const LONG = ['spsa_inputs', 'datagen_custom_genfens'];
// The model: what the editor is showing, which build() turns back into a graph
const model = {
start : typeof root.start === 'string' ? root.start : '',
max_visits : root.max_visits == null ? '' : String(root.max_visits),
max_steps : root.max_steps == null ? '' : String(root.max_steps),
steps : Object.entries(isObj(root.steps) ? root.steps : {}).map(([id, step]) => ({
id : id,
name : (isObj(step) && step.name) || id,
kind : (isObj(step) && step.kind) || 'TEST',
payload : texts(isObj(step) ? step.payload : {}),
msg : '',
})),
edges : (Array.isArray(root.edges) ? root.edges : []).filter(isObj).map(edge => ({
from : edge.from,
on : edge.on,
to : edge.to == null ? '' : edge.to,
set : texts(edge.set),
})),
};
const sel = { step : null, edge : null };
let lastIssues = [];
const stepById = id => model.steps.find(step => step.id === id);
const nameOf = step => (step && (step.name || step.id)) || '';
// Small DOM helpers. Text always goes in as text, never as HTML
function el(tag, attrs, ...kids) {
const node = document.createElement(tag);
for (const [key, value] of Object.entries(attrs || {})) {
if (value === false || value == null) continue;
if (key === 'class') node.className = value;
else node.setAttribute(key, value === true ? '' : value);
}
for (const kid of kids.flat()) {
if (kid != null) node.append(kid);
}
return node;
}
function svgEl(tag, attrs, ...kids) {
const node = document.createElementNS(NS, tag);
for (const [key, value] of Object.entries(attrs || {})) node.setAttribute(key, value);
kids.forEach(kid => node.append(kid));
return node;
}
function button(content, handler, cls) {
const node = el('button', { type : 'button', class : 'anchorbutton ' + (cls || 'btn-blue') + ' ed-small' }, content);
node.addEventListener('click', handler);
return node;
}
// Steps and what they need
function needed(step) {
const keys = (meta.required[step.kind] || []).slice();
if (step.kind === 'TEST') {
const mode = step.payload.test_mode || 'SPRT';
(meta.conditional[mode] || []).forEach(key => keys.push(key));
}
return keys;
}
function fieldsFor(step) {
const keys = needed(step);
OPTIONAL.forEach(key => { if (key === 'dev_bench' || step.kind !== 'TUNE') keys.push(key); });
return keys.filter((key, index) => keys.indexOf(key) === index);
}
function scaffold(step) {
const defaults = meta.defaults[step.kind] || {};
needed(step).forEach(key => {
if (!(key in step.payload)) step.payload[key] = defaults[key] == null ? '' : String(defaults[key]);
});
}
function nextId() {
const taken = new Set(model.steps.map(step => step.id));
let n = model.steps.length + 1;
while (taken.has('step' + n)) n++;
return 'step' + n;
}
// A step that follows another starts out as a copy of it: the next one is usually the same test, longer
function newStep(kind, from) {
const source = from && from.kind === kind ? from.payload : meta.defaults[kind];
const step = { id : nextId(), name : 'Step ' + (model.steps.length + 1), kind : kind, payload : texts(source), msg : '' };
scaffold(step);
model.steps.push(step);
return step;
}
function changeKind(step, kind) {
const allowed = new Set(meta.allowed);
const kept = {};
Object.keys(step.payload).forEach(key => { if (allowed.has(key)) kept[key] = step.payload[key]; });
step.kind = kind;
step.payload = Object.assign(texts(meta.defaults[kind]), kept);
scaffold(step);
}
function removeStep(step) {
model.steps.splice(model.steps.indexOf(step), 1);
model.edges = model.edges.filter(edge => edge.from !== step.id && edge.to !== step.id);
if (model.start === step.id) model.start = model.steps[0].id;
select(model.start);
changed();
}
// Turn the model back into a graph
function build() {
const steps = {};
model.steps.forEach(step => {
const payload = {};
Object.keys(step.payload).forEach(key => { if (key.trim()) payload[key.trim()] = step.payload[key]; });
steps[step.id] = { name : step.name, kind : step.kind, payload : payload };
});
const edges = model.edges.map(edge => {
const out = { from : edge.from, on : edge.on, to : edge.to === '' ? null : edge.to };
const set = {};
Object.keys(edge.set).forEach(key => { if (key.trim()) set[key.trim()] = edge.set[key]; });
if (Object.keys(set).length) out.set = set;
return out;
});
const graph = { version : 1, start : model.start, steps : steps, edges : edges };
const visits = parseInt(model.max_visits, 10);
const total = parseInt(model.max_steps, 10);
if (!isNaN(visits)) graph.max_visits = visits;
if (!isNaN(total)) graph.max_steps = total;
return graph;
}
// The flow, drawn by the server, with the very same code that draws a run
let timer = null;
let ticket = 0;
function changed() {
drawHint();
clearTimeout(timer);
timer = setTimeout(refresh, 250);
}
async function refresh() {
const mine = ++ticket;
const body = new FormData();
body.append('csrfmiddlewaretoken', token);
body.append('graph', JSON.stringify(build()));
try {
const response = await fetch('/pipelines/preview/', { method : 'POST', body : body, credentials : 'same-origin' });
const data = await response.json();
if (mine !== ticket) return;
drawCanvas(data.svg || '');
showIssues(data.issues || [{ level : 'error', step : null, message : data.error || 'The check failed' }]);
} catch (error) {
if (mine !== ticket) return;
showIssues([{ level : 'error', step : null, message : 'The flow could not be drawn. Reload the page and try again' }]);
}
}
const nodeFor = id => Array.from(stage.querySelectorAll('g.pl-node')).find(node => node.getAttribute('data-step') === id);
const edgeFor = index => Array.from(stage.querySelectorAll('g.pl-edge')).find(node => node.getAttribute('data-edge') === String(index));
function drawCanvas(markup) {
closeMenu();
if (!markup) {
stage.replaceChildren(el('p', { class : 'ed-note' }, 'The flow cannot be drawn yet. The checks below say why.'));
return;
}
stage.innerHTML = markup; // Escaped by the server, which is the only place that writes it
const svg = stage.querySelector('svg');
if (!svg) return;
// A wide invisible copy of every arrow, so that a thin line is easy to hit
svg.querySelectorAll('g.pl-edge').forEach(group => {
const line = group.querySelector('.pl-line');
if (!line) return;
const hit = line.cloneNode(false);
hit.setAttribute('class', 'ed-hit');
hit.removeAttribute('marker-end');
group.insertBefore(hit, line);
});
// A + on top of every step: this is where the next step comes from
svg.querySelectorAll('g.pl-node').forEach(group => {
const box = group.querySelector('.pl-box');
if (!box) return;
const x = Number(box.getAttribute('x')) + Number(box.getAttribute('width')) / 2;
const y = Number(box.getAttribute('y'));
svg.append(svgEl('g', { class : 'ed-plus', 'data-plus' : group.getAttribute('data-step') },
svgEl('title', {}, 'Add what happens next'),
svgEl('circle', { cx : x, cy : y, r : 11 }),
svgEl('path', { d : 'M' + (x - 5) + ' ' + y + ' h10 M' + x + ' ' + (y - 5) + ' v10' })));
});
applyMarks();
}
function applyMarks() {
stage.querySelectorAll('.ed-sel, .ed-bad, .ed-warn').forEach(node => node.classList.remove('ed-sel', 'ed-bad', 'ed-warn'));
const worst = {};
lastIssues.forEach(issue => {
if (typeof issue.step !== 'string') return;
if (issue.level === 'error') worst[issue.step] = 'ed-bad';
else if (issue.level === 'warning' && !worst[issue.step]) worst[issue.step] = 'ed-warn';
});
Object.keys(worst).forEach(id => { const node = nodeFor(id); if (node) node.classList.add(worst[id]); });
if (sel.step !== null) { const node = nodeFor(sel.step); if (node) node.classList.add('ed-sel'); }
if (sel.edge !== null) { const node = edgeFor(sel.edge); if (node) node.classList.add('ed-sel'); }
}
stage.addEventListener('click', event => {
const plus = event.target.closest('.ed-plus');
if (plus) { openMenu(plus.getAttribute('data-plus')); return; }
const edge = event.target.closest('g.pl-edge');
if (edge) { selectEdge(Number(edge.getAttribute('data-edge'))); return; }
const node = event.target.closest('g.pl-node');
if (node) { select(node.getAttribute('data-step')); return; }
closeMenu();
});
// The + menu: what should start, and when
function closeMenu() { menu.hidden = true; }
function openMenu(stepId) {
const step = stepById(stepId);
const node = nodeFor(stepId);
const box = node && node.querySelector('.pl-box');
if (!step || !box) return;
const x = Number(box.getAttribute('x')) + Number(box.getAttribute('width')) / 2;
const y = Number(box.getAttribute('y'));
menu.replaceChildren(el('div', { class : 'ed-menu-title' }, 'After ' + nameOf(step)));
meta.outcomes.filter(outcome => !(IMPOSSIBLE[step.kind] || []).includes(outcome)).forEach(outcome => {
const exists = model.edges.some(edge => edge.from === stepId && edge.on === outcome);
const item = el('button', { type : 'button', class : 'ed-menu-item ed-menu-' + outcome, role : 'menuitem' },
el('i', { class : 'fa-solid ' + MENU_ICON[outcome] }), MENU_TEXT[outcome] || outcome,
exists ? el('small', {}, 'open') : null);
item.addEventListener('click', () => chain(stepId, outcome));
menu.append(item);
});
menu.style.left = Math.max(4, x - 96) + 'px';
menu.style.top = (y + 20) + 'px';
menu.hidden = false;
}
function chain(stepId, outcome) {
const from = stepById(stepId);
const existing = model.edges.find(edge => edge.from === stepId && edge.on === outcome);
if (existing) { selectEdge(model.edges.indexOf(existing)); return; }
if (model.steps.length >= meta.limits.steps) {
flash('A pipeline may have at most ' + meta.limits.steps + ' steps');
closeMenu();
return;
}
const next = newStep(from.kind, from);
model.edges.push({ from : stepId, on : outcome, to : next.id, set : {} });
select(next.id);
changed();
}
document.addEventListener('click', event => {
if (!event.target.closest('.ed-plus, #pl-menu')) closeMenu();
});
document.addEventListener('keydown', event => {
if (event.key === 'Escape') closeMenu();
});
// Selecting
function select(id) {
sel.step = id;
sel.edge = null;
closeMenu();
drawPanel();
applyMarks();
}
function selectEdge(index) {
const edge = model.edges[index];
if (!edge) return;
sel.step = edge.from;
sel.edge = index;
closeMenu();
drawPanel();
applyMarks();
const row = panel.querySelector('.ed-rule.ed-picked');
if (row) row.scrollIntoView({ block : 'nearest' });
}
function markRows() {
panel.querySelectorAll('.ed-rule').forEach(row => {
row.classList.toggle('ed-picked', Number(row.getAttribute('data-edge')) === sel.edge);
});
}
// The panel: the settings of the selected step, and what it leads to
function fillSelect(select, value, allowEnd) {
select.replaceChildren();
if (allowEnd) select.append(el('option', { value : '' }, 'end the pipeline'));
model.steps.forEach(step => select.append(el('option', { value : step.id }, 'start ' + nameOf(step))));
select.value = value;
}
function stepSelect(value, allowEnd, onChange) {
const select = el('select', { class : 'ed-step-select', 'data-end' : allowEnd ? '1' : '0', 'aria-label' : 'Step' });
fillSelect(select, value, allowEnd);
select.addEventListener('change', () => onChange(select.value));
return select;
}
function refreshSelects() {
panel.querySelectorAll('.ed-step-select').forEach(select => {
fillSelect(select, select.value, select.getAttribute('data-end') === '1');
});
}
function field(step, key, isRequired) {
const choices = CHOICES[key];
const current = step.payload[key] == null ? '' : step.payload[key];
let input;
if (choices) {
input = el('select', { 'aria-label' : fullLabel(key) }, choices.map(choice => el('option', { value : choice }, choice)));
if (!choices.includes(current)) input.append(el('option', { value : current }, current));
} else if (LONG.includes(key)) {
input = el('textarea', { rows : '4', spellcheck : 'false', 'aria-label' : fullLabel(key) });
} else {
input = el('input', { spellcheck : 'false', 'aria-label' : fullLabel(key) });
}
input.value = current;
const flag = () => input.classList.toggle('ed-empty', isRequired && input.value.trim() === '');
input.addEventListener(choices ? 'change' : 'input', () => {
step.payload[key] = input.value;
flag();
if (key === 'test_mode') { scaffold(step); drawPanel(); }
changed();
});
flag();
return el('div', { class : LONG.includes(key) ? 'ed-field ed-wide' : 'ed-field' },
el('label', {}, label(key) + (isRequired ? '' : ' (optional)')), input);
}
// The settings that a rule changes for the step that it starts
function setEditor(edge) {
const box = el('div');
const preferred = ['dev_time_control', 'base_time_control', 'test_bounds', 'test_confidence', 'test_max_games',
'dev_branch', 'base_branch', 'dev_options', 'base_options', 'dev_network', 'base_network', 'priority', 'throughput', 'workload_size', 'book_name'];
const allowed = new Set(meta.allowed);
const keys = preferred.filter(key => allowed.has(key)).concat(meta.allowed.filter(key => !preferred.includes(key)));
const draw = () => {
box.replaceChildren();
Object.keys(edge.set).forEach(key => {
const input = el('input', { spellcheck : 'false', 'aria-label' : fullLabel(key) });
input.value = edge.set[key];
input.addEventListener('input', () => { edge.set[key] = input.value; changed(); });
const remove = button('\u00d7', () => { delete edge.set[key]; draw(); changed(); }, 'btn-red');
remove.title = 'Stop changing this setting';
box.append(el('div', { class : 'ed-set-row' }, el('label', {}, fullLabel(key)), input, remove));
});
const pick = el('select', { 'aria-label' : 'Change a setting' },
el('option', { value : '' }, 'Change a setting\u2026'),
keys.filter(key => !(key in edge.set)).map(key => el('option', { value : key }, fullLabel(key))));
pick.addEventListener('change', () => {
if (!pick.value) return;
const target = stepById(edge.to) || stepById(edge.from);
edge.set[pick.value] = (target && target.payload[pick.value]) || '';
draw();
changed();
});
box.append(pick);
};
draw();
return box;
}
function ruleRow(edge, index) {
const on = el('select', { 'aria-label' : 'Outcome' }, meta.outcomes.map(outcome => el('option', { value : outcome }, OUTCOME_TEXT[outcome] || outcome)));
on.value = edge.on;
on.addEventListener('change', () => { edge.on = on.value; changed(); });
const to = stepSelect(edge.to, true, value => { edge.to = value; changed(); });
const remove = button('\u00d7', () => {
model.edges.splice(model.edges.indexOf(edge), 1);
sel.edge = null;
drawPanel();
applyMarks();
changed();
}, 'btn-red');
remove.title = 'Remove this rule';
const more = el('details', { open : Object.keys(edge.set).length > 0 || sel.edge === index },
el('summary', {}, 'Change settings for the step that starts'), setEditor(edge));
const row = el('div', { class : 'ed-box ed-rule' + (sel.edge === index ? ' ed-picked' : ''), 'data-edge' : String(index) },
el('div', { class : 'ed-inline' }, 'If', on, 'then', to, remove), more);
row.addEventListener('click', () => { sel.edge = index; applyMarks(); markRows(); });
return row;
}
function addRule(step) {
const used = model.edges.filter(edge => edge.from === step.id).map(edge => edge.on);
const options = meta.outcomes.filter(outcome => !(IMPOSSIBLE[step.kind] || []).includes(outcome));
model.edges.push({ from : step.id, on : options.find(outcome => !used.includes(outcome)) || 'any', to : '', set : {} });
sel.edge = model.edges.length - 1;
drawPanel();
applyMarks();
changed();
}
function drawPanel() {
panel.replaceChildren();
const step = stepById(sel.step);
if (!step) {
panel.append(el('div', { class : 'card-head' }, el('h2', { class : 'card-title' }, 'Step')),
el('p', { class : 'ed-note ed-pad' }, 'Click a step in the flow to change it.'));
return;
}
const head = el('div', { class : 'card-head' }, el('h2', { class : 'card-title' }, 'Step'),
model.start === step.id
? el('span', { class : 'ed-tag' }, 'First step')
: button('Make this the first step', () => { model.start = step.id; drawPanel(); changed(); }));
const body = el('div', { class : 'ed-pad' });
const name = el('input', { maxlength : '64', required : true, style : 'width: 100%', 'aria-label' : 'Step name' });
name.value = step.name;
name.addEventListener('input', () => { step.name = name.value; refreshSelects(); changed(); });
const kind = el('select', { 'aria-label' : 'Kind' }, meta.kinds.map(k => el('option', { value : k }, KIND_LABEL[k] || k)));
kind.value = step.kind;
kind.addEventListener('change', () => { changeKind(step, kind.value); drawPanel(); changed(); });
body.append(el('div', { class : 'ed-inline', style : 'align-items: flex-end' },
el('div', { style : 'flex: 1 1 9rem' }, el('label', {}, 'Name'), name),
el('div', {}, el('label', {}, 'Kind'), kind)));
if (step.msg) body.append(el('p', { class : 'ed-note' }, step.msg));
// Start from a test that already exists
if (step.kind === 'TEST') {
const number = el('input', { type : 'number', min : '1', placeholder : 'Test #', 'aria-label' : 'Test number', style : 'width: 6.5rem' });
const copy = button('Copy settings', async () => {
const id = parseInt(number.value, 10);
if (!id) { step.msg = 'Type the number of a test first'; drawPanel(); return; }
try {
const response = await fetch('/pipelines/test-fields/' + id + '/', { credentials : 'same-origin' });
const data = await response.json();
if (!response.ok) { step.msg = data.error || 'Could not copy that test'; drawPanel(); return; }
step.payload = texts(data.payload);
scaffold(step);
step.msg = 'Copied from test #' + id + '. Check the branches before saving';
} catch (error) {
step.msg = 'Could not copy that test';
}
drawPanel();
changed();
});
body.append(el('div', { style : 'margin-top: .8rem' }, el('label', {}, 'Start from a test that already exists'),
el('div', { class : 'ed-inline' }, number, copy)));
}
// The settings, in the same groups as the pages that create a test
const required = needed(step);
const groups = {};
fieldsFor(step).forEach(key => { (groups[groupOf(key)] = groups[groupOf(key)] || []).push(key); });
GROUP_ORDER.forEach(title => {
if (!groups[title]) return;
const grid = el('div', { class : 'ed-grid' }, groups[title].map(key => field(step, key, required.includes(key))));
const empty = groups[title].some(key => required.includes(key) && String(step.payload[key] == null ? '' : step.payload[key]).trim() === '');
body.append(el('details', { class : 'ed-group', open : title === 'Match' || (title !== 'Advanced' && empty) },
el('summary', {}, GROUP_TITLE[title]), grid));
});
// What it leads to
body.append(el('h3', { class : 'ed-h' }, 'What happens next'));
let leads = 0;
model.edges.forEach((edge, index) => {
if (edge.from !== step.id) return;
leads++;
body.append(ruleRow(edge, index));
});
if (!leads) body.append(el('p', { class : 'ed-note' }, 'Nothing: the pipeline ends after this step. Press + above the step in the flow, or add a rule here.'));
const remove = button('Remove this step', () => removeStep(step), 'btn-red');
remove.disabled = model.steps.length < 2;
body.append(el('div', { class : 'ed-inline', style : 'margin-top: .6rem' }, button('Add rule', () => addRule(step)), remove));
panel.append(head, body);
}
// Checks, from the server, so that they are the very same rules that a run uses
function showIssues(list) {
lastIssues = list;
checks.replaceChildren();
if (!list.length) {
checks.append(el('li', { class : 'pl-check pl-check-ok' }, el('i', { class : 'fa-solid fa-circle-check' }), el('span', {}, 'No problems found')));
applyMarks();
return;
}
list.forEach(issue => {
const icon = issue.level === 'error' ? 'fa-circle-exclamation' : issue.level === 'warning' ? 'fa-triangle-exclamation' : 'fa-circle-info';
const who = issue.name || (typeof issue.step === 'string' ? issue.step : '');
const jump = typeof issue.step === 'string' && stepById(issue.step);
const item = el('li', { class : 'pl-check pl-check-' + issue.level + (jump ? ' ed-jump' : '') },
el('i', { class : 'fa-solid ' + icon }),
el('span', {}, who ? el('strong', {}, who) : null, who ? ' ' : null, issue.message));
if (jump) item.addEventListener('click', () => select(issue.step));
checks.append(item);
});
applyMarks();
}
// The line under the flow
let flashTimer = null;
function flash(message) {
hint.textContent = message;
hint.classList.add('ed-hint-warn');
clearTimeout(flashTimer);
flashTimer = setTimeout(drawHint, 4000);
}
function drawHint() {
hint.classList.remove('ed-hint-warn');
hint.textContent = model.steps.length === 1 && !model.edges.length
? 'This is the whole pipeline so far: one step, and then it ends. Press the + above the step to say what starts when it passes or fails.'
: 'Press + above a step to add what happens next. Click a step to change its settings, or the label on an arrow to change that rule.';
}
// Toolbar, limits and saving
['TEST', 'TUNE', 'DATAGEN'].forEach(kind => {
document.getElementById('pl-add-' + kind.toLowerCase()).addEventListener('click', () => {
if (model.steps.length >= meta.limits.steps) {
flash('A pipeline may have at most ' + meta.limits.steps + ' steps');
return;
}
const step = newStep(kind, null);
select(step.id);
changed();
});
});
const visitsField = document.getElementById('pl-visits');
const totalField = document.getElementById('pl-total');
visitsField.max = meta.limits.visits;
totalField.max = meta.limits.total;
visitsField.value = model.max_visits;
totalField.value = model.max_steps;
visitsField.addEventListener('input', () => { model.max_visits = visitsField.value; changed(); });
totalField.addEventListener('input', () => { model.max_steps = totalField.value; changed(); });
form.addEventListener('submit', () => {
document.getElementById('pl-graph').value = JSON.stringify(build());
});
// Go
if (!model.steps.length) {
const first = { id : 'step1', name : 'Step 1', kind : 'TEST', payload : texts(meta.defaults.TEST), msg : '' };
scaffold(first);
model.steps.push(first);
}
if (!model.steps.some(step => step.id === model.start)) model.start = model.steps[0].id;
sel.step = model.start;
drawPanel();
drawHint();
refresh();
})();
</script>
{% endblock %}
+92
View File
@@ -0,0 +1,92 @@
{% extends "OpenBench/base.html" %}
{% block page_head %}
<div>
<a class="crumb" href="/pipelines/"><i class="fa-solid fa-chevron-left"></i> Pipelines</a>
<h1 class="page-title">New pipeline</h1>
<p class="page-sub">Type a branch and press Enter. Everything else is filled in like Create Test, and the first test starts right away</p>
</div>
{% endblock %}
{% block content %}
<style>
.quick-more { margin-top: 14px; }
.quick-more summary { cursor: pointer; margin-bottom: 12px; color: var(--color-font2, inherit); font-size: 13px; }
.quick-actions { display: flex; flex-wrap: wrap; gap: .75rem; align-items: center; }
.quick-hint { margin-top: 1rem; }
</style>
<form method="post" action="/pipelines/quick/" autocomplete="off">
{% csrf_token %}
<div class="form">
<div class="col">
<h3> What to test </h3>
<div class="row">
<label for="dev_branch"> Dev Branch </label>
<input id="dev_branch" name="dev_branch" value="{{ form.dev_branch }}" placeholder="The branch to test" spellcheck="false" autofocus required>
</div>
<div class="row">
<label for="first"> First Test </label>
<select id="first" name="first">
{% for choice in choices %}
<option value="{{ choice.name }}"{% if choice.name == form.first %} selected{% endif %}>{{ choice.name }}{% if choice.time %} ({{ choice.time }}){% endif %}</option>
{% endfor %}
</select>
</div>
<div class="row">
<label for="then"> If It Passes </label>
<select id="then" name="then">
<option value=""{% if not form.then %} selected{% endif %}>Stop there</option>
{% for choice in choices %}
<option value="{{ choice.name }}"{% if choice.name == form.then %} selected{% endif %}>Then {{ choice.name }}{% if choice.time %} ({{ choice.time }}){% endif %}</option>
{% endfor %}
</select>
</div>
<details class="quick-more"{% if more %} open{% endif %}>
<summary> More options </summary>
{% if engines|length > 1 %}
<div class="row">
<label for="engine"> Engine </label>
<select id="engine" name="engine" onchange="location.search = '?engine=' + encodeURIComponent(this.value) + '&amp;dev_branch=' + encodeURIComponent(document.getElementById('dev_branch').value);">
{% for name in engines %}
<option value="{{ name }}"{% if name == engine %} selected{% endif %}>{{ name }}</option>
{% endfor %}
</select>
</div>
{% else %}
<input type="hidden" name="engine" value="{{ engine }}">
{% endif %}
<div class="row">
<label for="base_branch"> Base Branch </label>
<input id="base_branch" name="base_branch" value="{{ form.base_branch }}" placeholder="{% if base %}{{ base }}{% else %}The branch to compare against{% endif %}" spellcheck="false"{% if not base %} required{% endif %}>
</div>
<div class="row">
<label for="name"> Name </label>
<input id="name" name="name" value="{{ form.name }}" placeholder="The branch, and what runs" maxlength="128" spellcheck="false">
</div>
</details>
</div>
</div>
<div class="form-actions">
<div class="quick-actions">
<button type="submit" name="action" value="run" class="anchorbutton btn-blue">Run pipeline</button>
<button type="submit" name="action" value="save" class="anchorbutton btn-start">Save without running</button>
</div>
</div>
</form>
<p class="muted-small quick-hint">Need to retry, branch on a failure, or tune? <a href="/pipelines/new/">Draw the flow in the editor</a>.</p>
{% endblock %}
+86
View File
@@ -0,0 +1,86 @@
{% extends "OpenBench/base.html" %}
{% load static %}
{% block scripts %}
<script src="{% static 'pipeline.js' %}?{{ static_version }}" defer></script>
{% endblock %}
{% block page_head %}
<div>
<a class="crumb" href="/pipelines/{{ pipeline.id }}/"><i class="fa-solid fa-chevron-left"></i> {{ pipeline.name }}</a>
<h1 class="page-title">Run {{ run.id }}</h1>
</div>
{% endblock %}
{% block content %}
<div id="pl-live" data-signature="{{ signature }}" data-running="{{ live|yesno:'true,false' }}">
<div class="pl-toolbar">
<span class="badge {{ state.badge }}">{{ state.label }}</span>
{% if can_manage and live %}
<form method="post" action="/pipelines/run/{{ run.id }}/cancel/"
onsubmit="return confirm('Cancel this run? Nothing more will start. Tests that already started keep running.');">
{% csrf_token %}
<button class="anchorbutton btn-red" type="submit">Cancel run</button>
</form>
{% endif %}
</div>
<dl class="ev-meta">
<div><dt>Started</dt><dd><span class="timestamp">{{ run.started|date:"U" }}</span></dd></div>
<div><dt>Started by</dt><dd>{{ run.starter|capfirst }}</dd></div>
<div><dt>Tests created</dt><dd>{{ rows|length }}</dd></div>
<div><dt>Pipeline</dt><dd><a href="/pipelines/{{ pipeline.id }}/">{{ pipeline.name }}</a></dd></div>
</dl>
<div class="card">
<div class="card-head"><h2 class="card-title">Path taken</h2></div>
<div class="pl-scroll">{{ svg|safe }}</div>
</div>
<div class="card">
<div class="card-head">
<h2 class="card-title">Tests</h2>
<span class="count">{{ rows|length }}</span>
</div>
<table class="stripes">
<tr class="table-header">
<th>Step</th>
<th>How it started</th>
<th>Status</th>
<th>Test</th>
</tr>
{% for row in rows %}
<tr>
<td class="col-test">{{ row.name }}</td>
<td>{{ row.after }}</td>
<td>
<span class="badge {{ row.state.badge }}">{{ row.state.label }}</span>
{% if row.waiting %}<div class="muted-small">Waiting for an approver to approve the test</div>{% endif %}
{% if row.step.message %}<div class="muted-small pl-message">{{ row.step.message }}</div>{% endif %}
</td>
<td>{% if row.url %}<a href="{{ row.url }}">Test {{ row.step.test_id }}</a>{% else %}<span class="muted">Not created</span>{% endif %}</td>
</tr>
{% endfor %}
</table>
</div>
{% if run.notes %}
<div class="card">
<div class="card-head"><h2 class="card-title">Why it went this way</h2></div>
<ul class="pl-checks">
{% for note in run.notes %}
<li class="pl-check pl-check-info"><i class="fa-solid fa-circle-info"></i><span>{{ note }}</span></li>
{% endfor %}
</ul>
</div>
{% endif %}
</div>
{% endblock %}
+77
View File
@@ -0,0 +1,77 @@
{% extends "OpenBench/base.html" %}
{% block page_head %}
<div>
<h1 class="page-title">Pipelines</h1>
<p class="page-sub">Run a test, then let its result decide what runs next</p>
</div>
<div class="page-actions">
<a class="anchorbutton btn-blue" href="/pipelines/quick/">New pipeline</a>
<a class="anchorbutton btn-start" href="/pipelines/new/">Flow editor</a>
</div>
{% endblock %}
{% block content %}
<div class="stat-grid">
<div class="stat-card stat-green">
<div class="stat-icon"><i class="fa-solid fa-play"></i></div>
<div>
<div class="stat-value">{{ running }}</div>
<div class="stat-label">Running now</div>
</div>
</div>
<div class="stat-card">
<div class="stat-icon"><i class="fa-solid fa-diagram-project"></i></div>
<div>
<div class="stat-value">{{ total }}</div>
<div class="stat-label">Pipelines</div>
</div>
</div>
<div class="stat-card stat-yellow">
<div class="stat-icon"><i class="fa-solid fa-pause"></i></div>
<div>
<div class="stat-value">{{ paused }}</div>
<div class="stat-label">Paused</div>
</div>
</div>
</div>
{% if rows %}
<table class="hoverable">
<tr class="table-header">
<th>Pipeline</th>
<th>Author</th>
<th class="numeric">Steps</th>
<th>Last run</th>
<th>Status</th>
</tr>
{% for row in rows %}
<tr data-href="/pipelines/{{ row.pipeline.id }}/">
<td class="col-test"><a href="/pipelines/{{ row.pipeline.id }}/">{{ row.pipeline.name }}</a></td>
<td>{{ row.pipeline.author|capfirst }}</td>
<td class="numeric">{{ row.steps }}</td>
<td class="col-date">{% if row.run %}<span class="timestamp">{{ row.run.started|date:"U" }}</span>{% else %}None yet{% endif %}</td>
<td><span class="badge {{ row.state.badge }}">{{ row.state.label }}</span></td>
</tr>
{% endfor %}
</table>
{% else %}
<div class="card">
<div class="empty-state">
<i class="fa-solid fa-diagram-project"></i>
<p>No pipelines yet.</p>
<p class="muted-small">A pipeline starts a test and picks the next one from the result. Use New pipeline to create the first one.</p>
</div>
</div>
{% endif %}
{% endblock %}
+8
View File
@@ -17,6 +17,14 @@
{% block content %}
{% if pipeline_step %}
<div class="pl-chip">
<i class="fa-solid fa-diagram-project"></i>
<span>Step <strong>{{ pipeline_step.name }}</strong> of <a href="/pipelines/run/{{ pipeline_step.run_id }}/">{{ pipeline_step.pipeline }}</a></span>
{% if pipeline_step.after %}<span class="muted">{{ pipeline_step.after }}</span>{% endif %}
</div>
{% endif %}
<div class="workload-container{% if type == "TUNE" %} tune-page{% endif %}">
{% if type == "TUNE" %}<div class="tune-side">{% endif %}
+304
View File
@@ -0,0 +1,304 @@
#!/usr/bin/python3
import os
import sys
import unittest
# Needed to include from ../OpenBench/pipeline_defaults.py, which has no Django dependencies
PARENT = os.path.join(os.path.dirname(os.path.abspath(__file__)), os.path.pardir)
sys.path.insert(0, os.path.abspath(PARENT))
from OpenBench.pipeline_defaults import *
from OpenBench.pipeline_graph import ALLOWED_FIELDS, REQUIRED_FIELDS, has_errors, validate_graph
# The shape of a real engine config ( Engines/Eleanor.json ), presets only
ENGINE = {
'source' : 'https://github.com/o/Engine',
'test_presets' : {
'default' : {
'base_branch' : 'main', 'book_name' : 'UHO.epd',
'test_bounds' : '[0.00, 5.00]', 'test_confidence' : '[0.05, 0.05]',
'win_adj' : 'movecount=3 score=400', 'draw_adj' : 'movenumber=40 movecount=8 score=10',
},
'STC' : { 'both_options' : 'Threads=1 Hash=8', 'both_time_control' : '8.0+0.08', 'workload_size' : 32 },
'LTC' : { 'both_options' : 'Threads=1 Hash=64', 'both_time_control' : '40.0+0.4', 'workload_size' : 8 },
},
}
NETWORKS = [
{ 'engine' : 'Engine', 'name' : 'old.nn', 'sha256' : 'aaaaaaaa', 'default' : False },
{ 'engine' : 'Engine', 'name' : 'newest.nn', 'sha256' : 'bbbbbbbb', 'default' : True },
{ 'engine' : 'Other', 'name' : 'other.nn', 'sha256' : 'cccccccc', 'default' : True },
]
def build(preset='STC', branch='dev', engine_config=ENGINE, **kwargs):
return test_payload('Engine', engine_config, preset, branch, **kwargs)
def with_presets(**presets):
return { 'source' : ENGINE['source'], 'test_presets' : dict(ENGINE['test_presets'], **presets) }
class PresetTests(unittest.TestCase):
def test_the_names_leave_out_the_defaults(self):
self.assertEqual(preset_names(ENGINE), ['STC', 'LTC'])
def test_an_engine_without_presets_has_none(self):
self.assertEqual(preset_names({}), [])
self.assertEqual(preset_names({ 'test_presets' : None }), [])
def test_both_goes_to_the_dev_and_the_base_alike(self):
payload, _ = build('LTC')
self.assertEqual((payload['dev_options'], payload['base_options']), ('Threads=1 Hash=64', 'Threads=1 Hash=64'))
self.assertEqual((payload['dev_time_control'], payload['base_time_control']), ('40.0+0.4', '40.0+0.4'))
def test_the_defaults_come_first_and_a_preset_wins_over_them(self):
engine = with_presets(Slow={ 'test_bounds' : '[-1.00, 3.00]', 'base_branch' : 'master',
'both_options' : 'Threads=1 Hash=8', 'both_time_control' : '1+1' })
payload, missing = build('Slow', engine_config=engine)
self.assertEqual(payload['test_bounds'], '[-1.00, 3.00]') # The preset
self.assertEqual(payload['base_branch'], 'master') # The preset
self.assertEqual(payload['test_confidence'], '[0.05, 0.05]') # The default, untouched
self.assertEqual(missing, [])
def test_the_time_control_of_a_preset_for_showing(self):
self.assertEqual((time_control(ENGINE, 'STC'), time_control(ENGINE, 'LTC')), ('8.0+0.08', '40.0+0.4'))
self.assertEqual(time_control(ENGINE, 'nope'), '')
class PayloadTests(unittest.TestCase):
def test_one_branch_is_all_that_it_takes(self):
payload, missing = build(branch='my-branch')
self.assertEqual(missing, [])
self.assertEqual(payload['dev_branch'], 'my-branch')
self.assertEqual(payload['base_branch'], 'main')
self.assertEqual(payload['test_mode'], 'SPRT')
self.assertEqual(payload['workload_size'], '32')
def test_it_starts_out_like_the_create_test_page(self):
payload, _ = build()
for key, value in FORM_DEFAULTS.items():
self.assertEqual(payload[key], value, key)
self.assertEqual(payload['syzygy_wdl'], 'DISABLED') # The page says disabled, whatever the editor said
self.assertEqual((payload['priority'], payload['throughput']), ('0', '1000'))
def test_every_setting_that_a_step_needs_is_there_and_is_text(self):
for preset in ('STC', 'LTC'):
payload, missing = build(preset)
self.assertEqual(missing, [])
for key in REQUIRED_FIELDS['TEST'] + ['test_bounds', 'test_confidence']:
self.assertIn(key, payload, key)
self.assertTrue(all(isinstance(value, str) for value in payload.values()))
self.assertTrue(set(payload) <= ALLOWED_FIELDS)
def test_engine_and_repo_are_the_engines_own_unless_the_profile_says_otherwise(self):
payload, _ = build()
self.assertEqual((payload['dev_engine'], payload['base_engine']), ('Engine', 'Engine'))
self.assertEqual((payload['dev_repo'], payload['base_repo']), ('https://github.com/o/Engine',) * 2)
payload, _ = build(repos={ 'Engine' : 'https://github.com/me/Engine' })
self.assertEqual((payload['dev_repo'], payload['base_repo']), ('https://github.com/me/Engine',) * 2)
payload, _ = build(repos={ 'Another' : 'https://github.com/me/Another' }) # Not for this engine
self.assertEqual(payload['dev_repo'], 'https://github.com/o/Engine')
payload, _ = build(repos=None) # A profile with nothing saved
self.assertEqual(payload['dev_repo'], 'https://github.com/o/Engine')
def test_the_base_branch_can_be_chosen(self):
payload, missing = build(base_branch='release')
self.assertEqual((payload['base_branch'], missing), ('release', []))
def test_a_missing_base_branch_is_reported_not_guessed(self):
engine = { 'source' : 'x', 'test_presets' : { 'STC' : ENGINE['test_presets']['STC'],
'default' : { 'book_name' : 'b.epd', 'test_bounds' : '[0.00, 5.00]', 'test_confidence' : '[0.05, 0.05]' } } }
self.assertEqual(build(engine_config=engine)[1], ['base_branch'])
self.assertEqual(build(engine_config=engine, base_branch='main')[1], [])
def test_what_the_presets_leave_out_is_reported(self):
engine = { 'source' : 'x', 'test_presets' : { 'default' : { 'base_branch' : 'main', 'book_name' : 'b.epd',
'test_bounds' : '[0.00, 5.00]', 'test_confidence' : '[0.05, 0.05]' }, 'Bare' : {} } }
payload, missing = build('Bare', engine_config=engine)
self.assertEqual(sorted(missing), ['base_options', 'base_time_control', 'dev_options', 'dev_time_control'])
self.assertEqual(payload['workload_size'], FALLBACKS['workload_size']) # These have a standard value
self.assertEqual(payload['win_adj'], FALLBACKS['win_adj'])
def test_an_engine_that_names_no_book_gets_the_first_one_there_is(self):
engine = with_presets(default={ 'base_branch' : 'main', 'test_bounds' : '[0.00, 5.00]', 'test_confidence' : '[0.05, 0.05]' })
self.assertEqual(build(engine_config=engine, books=['one.epd', 'two.epd'])[0]['book_name'], 'one.epd')
self.assertEqual(build(engine_config=engine)[1], ['book_name'])
def test_an_unknown_preset_only_has_the_defaults_to_go_on(self):
_, missing = build('nope')
self.assertIn('dev_time_control', missing)
def test_whatever_else_a_preset_holds_is_left_out(self):
engine = with_presets(Odd={ 'both_options' : 'Threads=1 Hash=8', 'both_time_control' : '1+1', 'rubbish' : 'x' })
payload, _ = build('Odd', engine_config=engine)
self.assertNotIn('rubbish', payload)
def test_a_bench_that_a_preset_gives_is_kept_and_otherwise_it_is_left_to_autofill(self):
self.assertNotIn('dev_bench', build()[0])
engine = with_presets(Fixed={ 'both_bench' : 12345, 'both_options' : 'Threads=1 Hash=8', 'both_time_control' : '1+1' })
payload, _ = build('Fixed', engine_config=engine)
self.assertEqual((payload['dev_bench'], payload['base_bench']), ('12345', '12345'))
class ModeTests(unittest.TestCase):
def test_a_preset_of_fixed_games_is_a_games_test(self):
engine = with_presets(Fixed={ 'both_options' : 'Threads=1 Hash=8', 'both_time_control' : '1+1', 'test_max_games' : 40000 })
payload, missing = build('Fixed', engine_config=engine)
self.assertEqual((payload['test_mode'], payload['test_max_games'], missing), ('GAMES', '40000', []))
self.assertNotIn('test_bounds', payload); self.assertNotIn('test_confidence', payload)
def test_sprt_leaves_the_number_of_games_out(self):
engine = with_presets(default=dict(ENGINE['test_presets']['default'], test_max_games=100))
payload, _ = build(engine_config=engine)
self.assertEqual(payload['test_mode'], 'GAMES') # The last word of the page, as it is for a person
self.assertEqual(build()[0]['test_mode'], 'SPRT')
self.assertNotIn('test_max_games', build()[0])
def test_bounds_after_games_make_it_sprt_again(self):
engine = with_presets(Both={ 'both_options' : 'Threads=1 Hash=8', 'both_time_control' : '1+1',
'test_max_games' : 100, 'test_bounds' : '[0.00, 2.00]' })
payload, _ = build('Both', engine_config=engine)
self.assertEqual(payload['test_mode'], 'SPRT')
self.assertNotIn('test_max_games', payload)
class NetworkTests(unittest.TestCase):
def test_the_default_network_of_the_engine(self):
self.assertEqual(build(networks=NETWORKS)[0]['dev_network'], 'bbbbbbbb')
self.assertEqual(build(networks=NETWORKS)[0]['base_network'], 'bbbbbbbb')
def test_no_default_means_no_network(self):
self.assertEqual(build(networks=NETWORKS[:1])[0]['dev_network'], '')
self.assertEqual(build()[0]['dev_network'], '')
def test_a_network_of_another_engine_is_never_used(self):
self.assertEqual(default_network(NETWORKS, 'Nothing'), '')
self.assertEqual(default_network(NETWORKS, 'Other'), 'cccccccc')
def test_the_last_default_wins_like_it_does_on_the_page(self):
twice = NETWORKS + [{ 'engine' : 'Engine', 'name' : 'later.nn', 'sha256' : 'dddddddd', 'default' : True }]
self.assertEqual(default_network(twice, 'Engine'), 'dddddddd')
def test_a_preset_may_name_a_network_or_give_its_hash(self):
for wanted in ('old.nn', 'aaaaaaaa'):
engine = with_presets(Net={ 'both_network' : wanted, 'both_options' : 'Threads=1 Hash=8', 'both_time_control' : '1+1' })
self.assertEqual(build('Net', engine_config=engine, networks=NETWORKS)[0]['dev_network'], 'aaaaaaaa', wanted)
def test_a_preset_may_ask_for_none(self):
engine = with_presets(Net={ 'both_network' : 'None', 'both_options' : 'Threads=1 Hash=8', 'both_time_control' : '1+1' })
self.assertEqual(build('Net', engine_config=engine, networks=NETWORKS)[0]['dev_network'], '')
def test_a_network_that_does_not_exist_changes_nothing(self):
engine = with_presets(Net={ 'both_network' : 'ghost.nn', 'both_options' : 'Threads=1 Hash=8', 'both_time_control' : '1+1' })
self.assertEqual(build('Net', engine_config=engine, networks=NETWORKS)[0]['dev_network'], 'bbbbbbbb')
def test_having_no_network_is_not_a_missing_setting(self):
self.assertEqual(build(networks=[])[1], [])
class BranchTests(unittest.TestCase):
def test_what_a_branch_may_look_like(self):
for text in ('main', 'feature/new-search_2', 'v1.2.3', 'a' * 255, '0' * 40, ' padded '):
self.assertEqual(clean_branch(text), text.strip(), text)
def test_what_it_may_not(self):
for text in (None, '', ' ', 'two words', 'tab\there', 'quote"d', "it's", 'back\\slash', 'a' * 256, 'new\nline'):
self.assertIsNone(clean_branch(text), repr(text))
class GraphTests(unittest.TestCase):
def steps(self, *presets):
return [(preset, build(preset)[0]) for preset in presets]
def test_a_graph_of_one_step_is_sound(self):
graph = quick_graph(self.steps('STC'))
self.assertFalse(has_errors(validate_graph(graph)))
self.assertEqual((graph['start'], list(graph['steps']), graph['edges']), ('step1', ['step1'], []))
def test_the_next_one_starts_when_the_one_before_passed(self):
graph = quick_graph(self.steps('STC', 'LTC'))
issues = validate_graph(graph)
self.assertFalse(has_errors(issues))
self.assertEqual([issue['level'] for issue in issues], ['info', 'info']) # Only "it ends here if it fails or stops"
self.assertEqual(graph['edges'], [{ 'from' : 'step1', 'on' : 'passed', 'to' : 'step2' }])
self.assertEqual([step['name'] for step in graph['steps'].values()], ['STC', 'LTC'])
def test_any_number_of_steps_make_a_chain(self):
graph = quick_graph(self.steps('STC', 'LTC', 'STC'))
self.assertFalse(has_errors(validate_graph(graph)))
self.assertEqual([(e['from'], e['to']) for e in graph['edges']], [('step1', 'step2'), ('step2', 'step3')])
def test_the_same_name_twice_is_told_apart(self):
graph = quick_graph(self.steps('STC', 'STC'))
self.assertEqual([step['name'] for step in graph['steps'].values()], ['STC', 'STC (2)'])
def test_a_long_name_is_cut_to_what_a_step_may_have(self):
graph = quick_graph([('x' * 100, build()[0])])
self.assertEqual(len(graph['steps']['step1']['name']), 64)
self.assertFalse(has_errors(validate_graph(graph)))
def test_each_step_has_settings_of_its_own(self):
graph = quick_graph(self.steps('STC', 'LTC'))
first, second = graph['steps']['step1']['payload'], graph['steps']['step2']['payload']
self.assertEqual((first['dev_time_control'], second['dev_time_control']), ('8.0+0.08', '40.0+0.4'))
self.assertEqual((first['dev_branch'], second['dev_branch']), ('dev', 'dev'))
def test_the_name_says_what_is_tested_and_what_runs(self):
self.assertEqual(quick_name('feature/x', ['STC', 'LTC']), 'feature/x: STC then LTC')
self.assertEqual(quick_name('feature/x', ['STC']), 'feature/x: STC')
def test_the_name_always_fits(self):
self.assertEqual(len(quick_name('b' * 255, ['STC', 'LTC'])), 128)
if __name__ == '__main__':
unittest.main()