Compare commits
20
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
c998e8c0d6 | ||
|
|
8077809d0b | ||
|
|
48027f1142 | ||
|
|
0122ede0f6 | ||
|
|
faf719ca31 | ||
|
|
2ed44ca053 | ||
|
|
011add1f23 | ||
|
|
ea1fed2627 | ||
|
|
edfc43a2be | ||
|
|
860bb6f0d2 | ||
|
|
752650fd31 | ||
|
|
55c38e6180 | ||
|
|
c916ed89b5 | ||
|
|
5146111ad5 | ||
|
|
71b4803120 | ||
|
|
2b80f804af | ||
|
|
0df26588f9 | ||
|
|
d456f2fecf | ||
|
|
429b765657 | ||
|
|
248b11473b |
No files matched your search
+1
-6
@@ -8,10 +8,6 @@
|
||||
"require_manual_registration" : false,
|
||||
"balance_engine_throughputs" : true,
|
||||
|
||||
"gitea_hosts" : [
|
||||
"https://gitea.rektdie.com"
|
||||
],
|
||||
|
||||
"books" : [
|
||||
"2moves_v1.epd",
|
||||
"3moves_FRC.epd",
|
||||
@@ -37,7 +33,6 @@
|
||||
"Prelude",
|
||||
"Simpler",
|
||||
"Stormphrax",
|
||||
"Impact",
|
||||
"Rigby"
|
||||
"Impact"
|
||||
]
|
||||
}
|
||||
@@ -1,78 +0,0 @@
|
||||
{
|
||||
"private" : false,
|
||||
"nps" : 780000,
|
||||
"source" : "https://gitea.rektdie.com/rektdie/Rigby",
|
||||
|
||||
"build" : {
|
||||
"path" : "",
|
||||
"compilers" : ["clang++"],
|
||||
"cpuflags" : [],
|
||||
"systems" : ["Linux", "Windows", "Darwin"]
|
||||
},
|
||||
|
||||
"test_presets" : {
|
||||
|
||||
"default" : {
|
||||
"base_branch" : "main",
|
||||
"book_name" : "UHO_Lichess_4852_v1.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=64",
|
||||
"both_time_control" : "8.0+0.08",
|
||||
"workload_size" : 32
|
||||
},
|
||||
|
||||
"LTC" : {
|
||||
"both_options" : "Threads=1 Hash=256",
|
||||
"both_time_control" : "40.0+0.4",
|
||||
"workload_size" : 8
|
||||
},
|
||||
|
||||
"Non-Regression STC" : {
|
||||
"test_bounds" : "[-5.00, 0.00]",
|
||||
"both_options" : "Threads=1 Hash=64",
|
||||
"both_time_control" : "8.0+0.08",
|
||||
"workload_size" : 32
|
||||
},
|
||||
|
||||
"Non-Regression LTC" : {
|
||||
"test_bounds" : "[-5.00, 0.00]",
|
||||
"both_options" : "Threads=1 Hash=256",
|
||||
"both_time_control" : "40.0+0.4",
|
||||
"workload_size" : 8
|
||||
}
|
||||
},
|
||||
|
||||
"tune_presets" : {
|
||||
|
||||
"default" : {
|
||||
"book_name" : "UHO_Lichess_4852_v1.epd",
|
||||
"win_adj" : "movecount=3 score=400",
|
||||
"draw_adj" : "movenumber=40 movecount=8 score=10"
|
||||
},
|
||||
|
||||
"STC" : {
|
||||
"dev_options" : "Threads=1 Hash=64",
|
||||
"dev_time_control" : "8.0+0.08"
|
||||
},
|
||||
|
||||
"LTC" : {
|
||||
"dev_options" : "Threads=1 Hash=256",
|
||||
"dev_time_control" : "40.0+0.4"
|
||||
}
|
||||
},
|
||||
|
||||
"datagen_presets" : {
|
||||
|
||||
"default" : {
|
||||
"win_adj" : "None",
|
||||
"draw_adj" : "None",
|
||||
"workload_size" : 128
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -27,3 +27,6 @@ django.contrib.admin.site.register(OpenBench.models.Result)
|
||||
django.contrib.admin.site.register(OpenBench.models.Test)
|
||||
django.contrib.admin.site.register(OpenBench.models.LogEvent)
|
||||
django.contrib.admin.site.register(OpenBench.models.Network)
|
||||
django.contrib.admin.site.register(OpenBench.models.Pipeline)
|
||||
django.contrib.admin.site.register(OpenBench.models.PipelineRun)
|
||||
django.contrib.admin.site.register(OpenBench.models.StepRun)
|
||||
+1
-6
@@ -25,7 +25,7 @@ import traceback
|
||||
|
||||
from OpenSite.settings import PROJECT_PATH
|
||||
|
||||
OPENBENCH_STATIC_VERSION = 'v5'
|
||||
OPENBENCH_STATIC_VERSION = 'v4'
|
||||
|
||||
OPENBENCH_CONFIG = None # Initialized by OpenBench/apps.py
|
||||
|
||||
@@ -101,11 +101,6 @@ def verify_general_config(conf):
|
||||
assert type(conf.get("require_manual_registration") == bool)
|
||||
assert type(conf.get("balance_engine_throughputs" ) == bool)
|
||||
|
||||
# Optional: Gitea servers that may serve engine sources, e.g. "https://gitea.example.com"
|
||||
hosts = conf.get("gitea_hosts", [])
|
||||
assert type(hosts) == list
|
||||
assert all(type(x) == str and x.startswith('https://') and x.count('/') == 2 for x in hosts)
|
||||
|
||||
def verify_engine_basics(conf):
|
||||
|
||||
assert type(conf.get('private')) == bool
|
||||
|
||||
@@ -1,214 +0,0 @@
|
||||
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
|
||||
# #
|
||||
# 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/>. #
|
||||
# #
|
||||
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
|
||||
|
||||
# Everything OpenBench needs to know about where engine sources live.
|
||||
#
|
||||
# Sources can be on Github, or on a Gitea server listed under "gitea_hosts" in
|
||||
# Config/config.json.
|
||||
#
|
||||
# Workers download sources with a plain GET and no credentials. Github archives
|
||||
# are public, so workers fetch them directly. For Gitea there are two modes:
|
||||
#
|
||||
# - Without a token, the repository must be readable anonymously (public, and
|
||||
# REQUIRE_SIGNIN_VIEW off on the Gitea server). The API is called without
|
||||
# credentials and workers get the plain archive link, exactly like Github.
|
||||
#
|
||||
# - With an API token in Config/credentials.gitea, private repositories and
|
||||
# servers that require a login work too. The token is never sent to any other
|
||||
# host. Workers cannot log in, so the server hands them a signed link to
|
||||
# /giteaSource/, which fetches the archive with the token and passes it on.
|
||||
#
|
||||
# The links are signed with the Gitea token itself, not Django's SECRET_KEY:
|
||||
# settings.py is part of the public repository, and a forged link would let
|
||||
# anyone read every repository the token can see. Replacing the token
|
||||
# invalidates the source links of tests created before.
|
||||
|
||||
import hashlib
|
||||
import hmac
|
||||
import os
|
||||
import re
|
||||
import urllib.parse
|
||||
|
||||
import requests
|
||||
|
||||
import OpenBench.config
|
||||
|
||||
from OpenSite.settings import PROJECT_PATH
|
||||
|
||||
GITHUB_PREFIX = 'https://github.com/'
|
||||
GITHUB_PATTERN = r'^https:\/\/github\.com\/[A-Za-z0-9-]+\/[A-Za-z0-9_.-]+\/?$'
|
||||
REPO_TAIL = r'\/[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+\/?$'
|
||||
REQUEST_TIMEOUT = 30
|
||||
|
||||
def gitea_hosts():
|
||||
return [host.rstrip('/') for host in OpenBench.config.OPENBENCH_CONFIG.get('gitea_hosts', [])]
|
||||
|
||||
def repo_prefixes():
|
||||
return [GITHUB_PREFIX] + ['%s/' % (host) for host in gitea_hosts()]
|
||||
|
||||
def gitea_host(repo):
|
||||
for host in gitea_hosts():
|
||||
if repo.startswith(host + '/'):
|
||||
return host
|
||||
return None
|
||||
|
||||
def is_gitea(repo):
|
||||
return gitea_host(repo) is not None
|
||||
|
||||
def is_valid_repo(repo):
|
||||
|
||||
if re.match(GITHUB_PATTERN, repo):
|
||||
return True
|
||||
|
||||
host = gitea_host(repo)
|
||||
return bool(host and re.match(REPO_TAIL, repo[len(host):]))
|
||||
|
||||
def owner_and_name(repo):
|
||||
host = gitea_host(repo) or GITHUB_PREFIX.rstrip('/')
|
||||
owner, name = repo[len(host):].strip('/').split('/')[:2]
|
||||
return owner, name
|
||||
|
||||
def api_base(repo):
|
||||
|
||||
if (host := gitea_host(repo)):
|
||||
return '%s/api/v1/repos/%s/%s' % ((host,) + owner_and_name(repo))
|
||||
|
||||
return repo.rstrip('/').replace('github.com', 'api.github.com/repos')
|
||||
|
||||
def read_gitea_token():
|
||||
path = os.path.join(PROJECT_PATH, 'Config', 'credentials.gitea')
|
||||
if os.path.exists(path):
|
||||
with open(path) as fin:
|
||||
return fin.readline().strip() or None
|
||||
|
||||
def gitea_headers():
|
||||
token = read_gitea_token()
|
||||
return { 'Authorization' : 'token %s' % (token) } if token else {}
|
||||
|
||||
def api_headers(engine, repo):
|
||||
|
||||
if is_gitea(repo):
|
||||
return gitea_headers()
|
||||
|
||||
import OpenBench.utils
|
||||
return OpenBench.utils.read_git_credentials(engine) or {}
|
||||
|
||||
def fetch_commit(repo, ref, headers):
|
||||
|
||||
# Returns { 'sha', 'tree', 'message' } for a branch, tag, or commit sha.
|
||||
# Raises when the reference cannot be resolved.
|
||||
|
||||
base = api_base(repo)
|
||||
bysha = bool(re.search('^[0-9a-fA-F]{40}$', ref))
|
||||
|
||||
if is_gitea(repo):
|
||||
# One endpoint resolves branches, tags and commit shas alike
|
||||
params = { 'sha' : ref, 'limit' : 1, 'stat' : 'false', 'verification' : 'false', 'files' : 'false' }
|
||||
data = requests.get(base + '/commits', params=params, headers=headers, timeout=REQUEST_TIMEOUT).json()
|
||||
data = data[0]
|
||||
|
||||
else:
|
||||
# Lookup branch or commit sha, but will fail for tags
|
||||
url = '%s/%s/%s' % (base, 'commits' if bysha else 'branches', ref)
|
||||
data = requests.get(url, headers=headers, timeout=REQUEST_TIMEOUT).json()
|
||||
|
||||
# Check to see if the branch name was actually a tag name
|
||||
if not bysha and 'commit' not in data:
|
||||
url = '%s/commits/%s' % (base, ref)
|
||||
data = requests.get(url, headers=headers, timeout=REQUEST_TIMEOUT).json()
|
||||
|
||||
# Actual branches have to go one layer deeper
|
||||
elif not bysha: data = data['commit']
|
||||
|
||||
# A lookup by sha must land on exactly that commit
|
||||
if bysha and data['sha'].lower() != ref.lower():
|
||||
raise ValueError('%s resolved to %s' % (ref, data['sha']))
|
||||
|
||||
return {
|
||||
'sha' : data['sha'],
|
||||
'tree' : (data['commit'].get('tree') or {}).get('sha'),
|
||||
'message' : data['commit']['message'],
|
||||
}
|
||||
|
||||
def commits_ahead(repo, dev_sha, base_sha, headers):
|
||||
|
||||
# Number of commits on base_sha that dev_sha does not have
|
||||
base = api_base(repo)
|
||||
|
||||
if is_gitea(repo):
|
||||
url = '%s/compare/%s...%s' % (base, dev_sha, base_sha)
|
||||
params = { 'verification' : 'false', 'files' : 'false' }
|
||||
return int(requests.get(url, params=params, headers=headers, timeout=REQUEST_TIMEOUT).json().get('total_commits', 0))
|
||||
|
||||
url = '%s/compare/%s...%s' % (base, dev_sha, base_sha)
|
||||
return int(requests.get(url, headers=headers, timeout=REQUEST_TIMEOUT).json().get('ahead_by', 0))
|
||||
|
||||
def compare_url(repo, base_sha, dev_sha):
|
||||
|
||||
repo = repo.rstrip('/')
|
||||
|
||||
if is_gitea(repo):
|
||||
return '%s/compare/%s...%s' % (repo, base_sha, dev_sha)
|
||||
|
||||
return '%s/compare/%s..%s' % (repo, base_sha, dev_sha)
|
||||
|
||||
def source_signature(repo, sha):
|
||||
|
||||
# Without a token there is nothing secret to sign with, and nothing to fetch with
|
||||
if not (key := read_gitea_token()):
|
||||
return None
|
||||
|
||||
message = ('openbench-gitea-source\n%s\n%s' % (repo.rstrip('/'), sha.lower())).encode('utf-8')
|
||||
return hmac.new(key.encode('utf-8'), message, hashlib.sha256).hexdigest()
|
||||
|
||||
def source_url(request, repo, commit):
|
||||
|
||||
# Github serves archives by tree sha, so identical trees share one download
|
||||
if not is_gitea(repo):
|
||||
return '%s/archive/%s.zip' % (repo.rstrip('/'), commit['tree'])
|
||||
|
||||
# Without a token the repository is public: workers download it directly.
|
||||
# Gitea archives are addressed by commit, not by tree.
|
||||
if not read_gitea_token():
|
||||
return '%s/archive/%s.zip' % (repo.rstrip('/'), commit['sha'])
|
||||
|
||||
query = urllib.parse.urlencode({
|
||||
'repo' : repo.rstrip('/'),
|
||||
'sha' : commit['sha'],
|
||||
'sig' : source_signature(repo, commit['sha']),
|
||||
})
|
||||
|
||||
return request.build_absolute_uri('/giteaSource/?%s' % (query))
|
||||
|
||||
def verify_source_request(repo, sha, sig):
|
||||
|
||||
if not (is_valid_repo(repo) and is_gitea(repo) and re.match('^[0-9a-fA-F]{40}$', sha or '')):
|
||||
return False
|
||||
|
||||
expected = source_signature(repo, sha)
|
||||
return bool(expected) and hmac.compare_digest(expected, sig or '')
|
||||
|
||||
def open_gitea_archive(repo, sha):
|
||||
|
||||
# Streams the .zip for one commit from the Gitea API
|
||||
url = '%s/archive/%s.zip' % (api_base(repo), sha)
|
||||
response = requests.get(url, headers=gitea_headers(), stream=True, timeout=REQUEST_TIMEOUT)
|
||||
response.raise_for_status()
|
||||
return response
|
||||
@@ -0,0 +1,46 @@
|
||||
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
|
||||
# #
|
||||
# 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/>. #
|
||||
# #
|
||||
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
|
||||
|
||||
|
||||
import time
|
||||
|
||||
from django.core.management.base import BaseCommand
|
||||
|
||||
class Command(BaseCommand):
|
||||
|
||||
help = 'Resolve Pipeline steps that missed their notification, and retry interrupted launches'
|
||||
|
||||
def add_arguments(self, parser):
|
||||
parser.add_argument('--loop', type=int, default=0, metavar='SECONDS',
|
||||
help='Keep running, checking again every SECONDS, instead of running once')
|
||||
|
||||
def handle(self, *args, **options):
|
||||
|
||||
import OpenBench.pipelines
|
||||
|
||||
while True:
|
||||
found = OpenBench.pipelines.catch_up()
|
||||
self.stdout.write('relaunched=%(relaunched)d resolved=%(resolved)d' % found)
|
||||
|
||||
if not options['loop']:
|
||||
break
|
||||
|
||||
self.stdout.flush()
|
||||
time.sleep(options['loop'])
|
||||
@@ -0,0 +1,52 @@
|
||||
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
|
||||
# #
|
||||
# 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/>. #
|
||||
# #
|
||||
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
|
||||
|
||||
|
||||
from django.core.management.base import BaseCommand, CommandError
|
||||
|
||||
class Command(BaseCommand):
|
||||
|
||||
help = 'Start a run of a Pipeline'
|
||||
|
||||
def add_arguments(self, parser):
|
||||
parser.add_argument('pipeline_id', type=int)
|
||||
parser.add_argument('--user', default=None, help='Who started it. Defaults to the Pipeline author')
|
||||
|
||||
def handle(self, *args, **options):
|
||||
|
||||
import OpenBench.pipelines
|
||||
from OpenBench.models import Pipeline
|
||||
|
||||
pipeline = Pipeline.objects.filter(id=options['pipeline_id']).first()
|
||||
if pipeline is None:
|
||||
raise CommandError('No such Pipeline')
|
||||
|
||||
run, issues = OpenBench.pipelines.start_pipeline(pipeline, options['user'])
|
||||
|
||||
for entry in issues:
|
||||
where = ' [%s]' % (entry['step']) if entry['step'] else ''
|
||||
self.stdout.write('%s%s: %s' % (entry['level'].upper(), where, entry['message']))
|
||||
|
||||
if run is None:
|
||||
raise CommandError('The Pipeline cannot run')
|
||||
|
||||
self.stdout.write('Started run #%d (%s)' % (run.id, run.status))
|
||||
for step in run.steps.order_by('id'):
|
||||
self.stdout.write(' %s: %s%s' % (step.step_key, step.status, ' ' + step.message if step.message else ''))
|
||||
@@ -22,6 +22,9 @@ from django.db.models import CharField, IntegerField, BooleanField, FloatField
|
||||
from django.db.models import JSONField, ForeignKey, DateTimeField, OneToOneField
|
||||
from django.db.models import CASCADE, PROTECT, Model
|
||||
from django.contrib.auth.models import User
|
||||
from django.core.exceptions import ValidationError
|
||||
|
||||
from OpenBench.pipeline_graph import validate_graph
|
||||
|
||||
class Engine(Model):
|
||||
|
||||
@@ -222,3 +225,68 @@ class PGN(Model):
|
||||
|
||||
def filename(self):
|
||||
return '%s.%s.%s.pgn.bz2' % (self.test_id, self.result_id, self.book_index)
|
||||
|
||||
class Pipeline(Model):
|
||||
|
||||
# A reusable description of tests to run, and what to do with their outcomes.
|
||||
# See OpenBench/pipeline_graph.py for what a graph looks like.
|
||||
|
||||
name = CharField(max_length=128)
|
||||
author = CharField(max_length=64) # Username. Workloads created by the Pipeline belong to them
|
||||
graph = JSONField(default=dict)
|
||||
enabled = BooleanField(default=True) # Disabled Pipelines neither start, nor carry on
|
||||
deleted = BooleanField(default=False)
|
||||
created = DateTimeField(auto_now_add=True)
|
||||
updated = DateTimeField(auto_now=True)
|
||||
|
||||
def __str__(self):
|
||||
return '[%d] %s' % (self.id or 0, self.name)
|
||||
|
||||
def issues(self):
|
||||
return validate_graph(self.graph)
|
||||
|
||||
def clean(self):
|
||||
# Never save a Pipeline that could not run. Used by the Admin forms
|
||||
errors = [i['message'] for i in self.issues() if i['level'] == 'error']
|
||||
if errors:
|
||||
raise ValidationError({ 'graph' : errors })
|
||||
|
||||
class PipelineRun(Model):
|
||||
|
||||
# One execution of a Pipeline. Works from a snapshot of the graph, so that
|
||||
# editing a Pipeline never changes a run that is already underway.
|
||||
|
||||
pipeline = ForeignKey('Pipeline', CASCADE, related_name='runs')
|
||||
graph = JSONField(default=dict)
|
||||
starter = CharField(max_length=64)
|
||||
status = CharField(max_length=16, default='RUNNING') # RUNNING, COMPLETED, ERROR, CANCELLED
|
||||
fired = IntegerField(default=0) # Workloads created so far, to enforce max_steps
|
||||
notes = JSONField(default=list, blank=True) # Why the run went the way it did
|
||||
started = DateTimeField(auto_now_add=True)
|
||||
updated = DateTimeField(auto_now=True)
|
||||
|
||||
def __str__(self):
|
||||
return 'Run %d of Pipeline %d (%s)' % (self.id or 0, self.pipeline_id, self.status)
|
||||
|
||||
class StepRun(Model):
|
||||
|
||||
# One workload that a PipelineRun has created, or is about to create
|
||||
#
|
||||
# QUEUED -> LAUNCHING -> RUNNING -> PASSED | FAILED | STOPPED
|
||||
# \-> ERROR ( the workload could not be created )
|
||||
|
||||
run = ForeignKey('PipelineRun', CASCADE, related_name='steps')
|
||||
parent = ForeignKey('StepRun', CASCADE, null=True, blank=True, related_name='children')
|
||||
step_key = CharField(max_length=32)
|
||||
via = CharField(max_length=16, blank=True, default='') # Outcome of the parent that led here
|
||||
kind = CharField(max_length=16)
|
||||
payload = JSONField(default=dict) # Final form fields, after any overrides
|
||||
status = CharField(max_length=16, default='QUEUED')
|
||||
test_id = IntegerField(default=0, db_index=True) # 0 until the workload exists
|
||||
message = CharField(max_length=512, blank=True, default='')
|
||||
created = DateTimeField(auto_now_add=True)
|
||||
updated = DateTimeField(auto_now=True)
|
||||
resolved = DateTimeField(null=True, blank=True)
|
||||
|
||||
def __str__(self):
|
||||
return '%s [%s] test=%d' % (self.step_key, self.status, self.test_id)
|
||||
@@ -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]
|
||||
@@ -0,0 +1,446 @@
|
||||
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
|
||||
# #
|
||||
# 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/>. #
|
||||
# #
|
||||
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
|
||||
|
||||
|
||||
# Pure-Python core of the Pipeline (test scheduler) feature. Nothing in here
|
||||
# touches Django, the database, or the network, so that all of the decision
|
||||
# making can be unit tested on its own ( see UnitTests/test_pipeline_graph.py ).
|
||||
#
|
||||
# A pipeline is described by a "graph", which is plain JSON:
|
||||
#
|
||||
# {
|
||||
# "version" : 1,
|
||||
# "start" : "stc",
|
||||
# "max_visits" : 3, # how many times one step may run in one run
|
||||
# "max_steps" : 20, # how many workloads one run may create at most
|
||||
# "steps" : {
|
||||
# "stc" : { "name" : "STC", "kind" : "TEST", "payload" : { ... } },
|
||||
# "ltc" : { "name" : "LTC", "kind" : "TEST", "payload" : { ... } },
|
||||
# },
|
||||
# "edges" : [
|
||||
# { "from" : "stc", "on" : "passed", "to" : "ltc" },
|
||||
# { "from" : "stc", "on" : "failed", "to" : "stc", "set" : { "test_bounds" : "[-1.00, 3.00]" } },
|
||||
# ]
|
||||
# }
|
||||
#
|
||||
# A step payload holds the very same fields as the Create Test / Tune / Datagen
|
||||
# forms do. An edge fires when its "from" step ends with the outcome "on", and
|
||||
# may override some payload fields for the step that it starts ( "set" ).
|
||||
|
||||
import re
|
||||
|
||||
SCHEMA_VERSION = 1
|
||||
|
||||
KINDS = ('TEST', 'TUNE', 'DATAGEN')
|
||||
OUTCOMES = ('passed', 'failed', 'stopped')
|
||||
EDGE_CONDITIONS = OUTCOMES + ('any',)
|
||||
|
||||
DEFAULT_MAX_VISITS = 3
|
||||
DEFAULT_MAX_STEPS = 20
|
||||
|
||||
LIMIT_STEPS = 30
|
||||
LIMIT_MAX_VISITS = 10
|
||||
LIMIT_MAX_STEPS = 50
|
||||
|
||||
ID_PATTERN = re.compile(r'^[A-Za-z0-9_-]{1,32}$')
|
||||
|
||||
# Statuses of a StepRun that still need attention from the scheduler
|
||||
ACTIVE_STATUSES = ('QUEUED', 'LAUNCHING', 'RUNNING')
|
||||
|
||||
_DEV = ['dev_engine', 'dev_repo', 'dev_branch', 'dev_network', 'dev_options', 'dev_time_control']
|
||||
_BASE = ['base_engine', 'base_repo', 'base_branch', 'base_network', 'base_options', 'base_time_control']
|
||||
_GENERAL = ['book_name', 'upload_pgns', 'priority', 'throughput', 'syzygy_wdl', 'syzygy_adj', 'win_adj', 'draw_adj']
|
||||
|
||||
# Mirrors what verify_workload() and create_workload() read from the form
|
||||
REQUIRED_FIELDS = {
|
||||
|
||||
'TEST' : _DEV + _BASE + _GENERAL + ['workload_size', 'test_mode'],
|
||||
|
||||
'TUNE' : _DEV + _GENERAL + [
|
||||
'spsa_alpha', 'spsa_gamma', 'spsa_A_ratio', 'spsa_iterations', 'spsa_pairs_per',
|
||||
'spsa_reporting_type', 'spsa_distribution_type', 'spsa_inputs' ],
|
||||
|
||||
'DATAGEN' : _DEV + _BASE + _GENERAL + [
|
||||
'workload_size', 'datagen_max_games', 'datagen_custom_genfens', 'datagen_play_reverses' ],
|
||||
}
|
||||
|
||||
# Fields that are only required for a given value of test_mode
|
||||
CONDITIONAL_FIELDS = {
|
||||
'SPRT' : ['test_bounds', 'test_confidence'],
|
||||
'GAMES' : ['test_max_games'],
|
||||
}
|
||||
|
||||
OPTIONAL_FIELDS = ['dev_bench', 'base_bench']
|
||||
|
||||
ALLOWED_FIELDS = set(OPTIONAL_FIELDS)
|
||||
for _fields in REQUIRED_FIELDS.values(): ALLOWED_FIELDS.update(_fields)
|
||||
for _fields in CONDITIONAL_FIELDS.values(): ALLOWED_FIELDS.update(_fields)
|
||||
|
||||
# Outcomes that can never happen for a kind of workload
|
||||
IMPOSSIBLE_OUTCOMES = {
|
||||
'TEST' : (),
|
||||
'TUNE' : ('failed',), # A finished tune counts as passed
|
||||
'DATAGEN' : ('failed',), # A finished datagen is always passing
|
||||
}
|
||||
|
||||
def issue(level, code, message, step=None):
|
||||
return { 'level' : level, 'code' : code, 'step' : step, 'message' : message }
|
||||
|
||||
def has_errors(issues):
|
||||
return any(entry['level'] == 'error' for entry in issues)
|
||||
|
||||
|
||||
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
|
||||
# VALIDATION #
|
||||
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
|
||||
|
||||
def validate_graph(graph):
|
||||
|
||||
""" Returns a list of issues. Any 'error' means the graph must not be saved
|
||||
or run. 'warning' and 'info' are meant to be shown, but not to block. """
|
||||
|
||||
issues = []
|
||||
|
||||
if not isinstance(graph, dict):
|
||||
return [issue('error', 'graph.invalid', 'The pipeline is not a valid object')]
|
||||
|
||||
if graph.get('version') != SCHEMA_VERSION:
|
||||
issues.append(issue('error', 'graph.version', 'Unsupported pipeline version'))
|
||||
|
||||
_validate_limits(graph, issues)
|
||||
|
||||
steps = graph.get('steps')
|
||||
if not isinstance(steps, dict) or not steps:
|
||||
issues.append(issue('error', 'steps.empty', 'A pipeline needs at least one step'))
|
||||
return issues
|
||||
|
||||
if len(steps) > LIMIT_STEPS:
|
||||
issues.append(issue('error', 'steps.limit', 'A pipeline may have at most %d steps' % (LIMIT_STEPS)))
|
||||
|
||||
for step_id, step in steps.items():
|
||||
_validate_step(step_id, step, issues)
|
||||
|
||||
if graph.get('start') not in steps:
|
||||
issues.append(issue('error', 'start.missing', 'The starting step does not exist'))
|
||||
|
||||
edges = graph.get('edges', [])
|
||||
if not isinstance(edges, list):
|
||||
issues.append(issue('error', 'edges.invalid', 'Edges must be a list'))
|
||||
edges = []
|
||||
|
||||
seen = set()
|
||||
for index, edge in enumerate(edges):
|
||||
_validate_edge(index, edge, steps, seen, issues)
|
||||
|
||||
# Structure checks only make sense on a graph that is otherwise sound
|
||||
if not has_errors(issues):
|
||||
_check_reachability(graph, issues)
|
||||
_check_coverage(graph, issues)
|
||||
_check_impossible_edges(graph, issues)
|
||||
_check_loops(graph, issues)
|
||||
|
||||
return issues
|
||||
|
||||
def _validate_limits(graph, issues):
|
||||
|
||||
for key, limit in (('max_visits', LIMIT_MAX_VISITS), ('max_steps', LIMIT_MAX_STEPS)):
|
||||
value = graph.get(key)
|
||||
|
||||
if value is None:
|
||||
continue
|
||||
|
||||
if isinstance(value, bool) or not isinstance(value, int) or not (1 <= value <= limit):
|
||||
issues.append(issue('error', 'limits.%s' % (key), '%s must be an integer in [1, %d]' % (key, limit)))
|
||||
|
||||
def _validate_step(step_id, step, issues):
|
||||
|
||||
if not isinstance(step_id, str) or not ID_PATTERN.match(step_id):
|
||||
issues.append(issue('error', 'step.id', 'Step ids may only use letters, digits, - and _ (max 32)', step_id))
|
||||
return
|
||||
|
||||
if not isinstance(step, dict):
|
||||
issues.append(issue('error', 'step.invalid', 'Step is not a valid object', step_id))
|
||||
return
|
||||
|
||||
name = step.get('name', step_id)
|
||||
if not isinstance(name, str) or not (1 <= len(name) <= 64):
|
||||
issues.append(issue('error', 'step.name', 'Step names must be 1 to 64 characters', step_id))
|
||||
|
||||
kind = step.get('kind')
|
||||
if kind not in KINDS:
|
||||
issues.append(issue('error', 'step.kind', 'Step kind must be one of %s' % (', '.join(KINDS)), step_id))
|
||||
return
|
||||
|
||||
payload = step.get('payload')
|
||||
if not isinstance(payload, dict):
|
||||
issues.append(issue('error', 'step.payload', 'Step has no settings', step_id))
|
||||
return
|
||||
|
||||
for key, value in payload.items():
|
||||
if isinstance(value, bool) or not isinstance(value, (str, int, float)):
|
||||
issues.append(issue('error', 'payload.type', 'Setting "%s" must be text or a number' % (key), step_id))
|
||||
|
||||
required = list(REQUIRED_FIELDS[kind])
|
||||
|
||||
if kind == 'TEST':
|
||||
mode = str(payload.get('test_mode', ''))
|
||||
if mode not in CONDITIONAL_FIELDS:
|
||||
issues.append(issue('error', 'payload.test_mode', 'Test mode must be SPRT or GAMES', step_id))
|
||||
else:
|
||||
required += CONDITIONAL_FIELDS[mode]
|
||||
|
||||
missing = [field for field in required if field not in payload]
|
||||
if missing:
|
||||
issues.append(issue('error', 'payload.missing', 'Missing settings: %s' % (', '.join(missing)), step_id))
|
||||
|
||||
unknown = [key for key in payload if key not in ALLOWED_FIELDS]
|
||||
if unknown:
|
||||
issues.append(issue('warning', 'payload.unknown', 'Unknown settings are ignored: %s' % (', '.join(unknown)), step_id))
|
||||
|
||||
def _validate_edge(index, edge, steps, seen, issues):
|
||||
|
||||
if not isinstance(edge, dict):
|
||||
issues.append(issue('error', 'edge.invalid', 'Edge #%d is not a valid object' % (index + 1)))
|
||||
return
|
||||
|
||||
source, target, cond = edge.get('from'), edge.get('to'), edge.get('on')
|
||||
|
||||
if source not in steps:
|
||||
issues.append(issue('error', 'edge.from', 'Edge #%d starts at an unknown step' % (index + 1)))
|
||||
|
||||
if target is not None and target not in steps:
|
||||
issues.append(issue('error', 'edge.to', 'Edge #%d leads to an unknown step' % (index + 1), source))
|
||||
|
||||
if cond not in EDGE_CONDITIONS:
|
||||
issues.append(issue('error', 'edge.on', 'Edge #%d needs a condition: %s' % (index + 1, ', '.join(EDGE_CONDITIONS)), source))
|
||||
|
||||
overrides = edge.get('set', {})
|
||||
if not isinstance(overrides, dict):
|
||||
issues.append(issue('error', 'edge.set', 'Edge #%d has invalid overrides' % (index + 1), source))
|
||||
overrides = {}
|
||||
|
||||
for key, value in overrides.items():
|
||||
if key not in ALLOWED_FIELDS:
|
||||
issues.append(issue('error', 'edge.set.key', 'Edge #%d overrides unknown setting "%s"' % (index + 1, key), source))
|
||||
if isinstance(value, bool) or not isinstance(value, (str, int, float)):
|
||||
issues.append(issue('error', 'edge.set.type', 'Edge #%d: "%s" must be text or a number' % (index + 1, key), source))
|
||||
|
||||
try:
|
||||
signature = (source, cond, target, tuple(sorted((k, str(v)) for k, v in overrides.items())))
|
||||
if signature in seen:
|
||||
issues.append(issue('error', 'edge.duplicate', 'Edge #%d duplicates an earlier edge' % (index + 1), source))
|
||||
seen.add(signature)
|
||||
except TypeError:
|
||||
pass # Unhashable garbage was already reported above
|
||||
|
||||
def _successors(graph):
|
||||
|
||||
result = { step_id : [] for step_id in graph['steps'] }
|
||||
for edge in graph.get('edges', []):
|
||||
if edge['to'] is not None:
|
||||
result[edge['from']].append(edge['to'])
|
||||
return result
|
||||
|
||||
def _check_reachability(graph, issues):
|
||||
|
||||
successors = _successors(graph)
|
||||
reached, stack = set(), [graph['start']]
|
||||
|
||||
while stack:
|
||||
step_id = stack.pop()
|
||||
if step_id in reached: continue
|
||||
reached.add(step_id)
|
||||
stack.extend(successors[step_id])
|
||||
|
||||
for step_id in graph['steps']:
|
||||
if step_id not in reached:
|
||||
issues.append(issue('warning', 'step.unreachable', 'This step can never start', step_id))
|
||||
|
||||
def _check_coverage(graph, issues):
|
||||
|
||||
outgoing = {}
|
||||
for edge in graph.get('edges', []):
|
||||
outgoing.setdefault(edge['from'], set()).add(edge['on'])
|
||||
|
||||
for step_id, step in graph['steps'].items():
|
||||
|
||||
conditions = outgoing.get(step_id)
|
||||
if not conditions or 'any' in conditions:
|
||||
continue # Terminal steps, or steps that always continue
|
||||
|
||||
possible = [o for o in OUTCOMES if o not in IMPOSSIBLE_OUTCOMES[step['kind']]]
|
||||
for outcome in possible:
|
||||
if outcome not in conditions:
|
||||
issues.append(issue('info', 'branch.uncovered', 'If this ends %s, the pipeline stops here' % (outcome), step_id))
|
||||
|
||||
def _check_impossible_edges(graph, issues):
|
||||
|
||||
for edge in graph.get('edges', []):
|
||||
kind = graph['steps'][edge['from']]['kind']
|
||||
if edge['on'] in IMPOSSIBLE_OUTCOMES[kind]:
|
||||
issues.append(issue('warning', 'edge.impossible', 'A %s can never end as %s, so this edge never fires' % (kind.lower(), edge['on']), edge['from']))
|
||||
|
||||
def _check_loops(graph, issues):
|
||||
|
||||
successors = _successors(graph)
|
||||
limit = graph.get('max_visits', DEFAULT_MAX_VISITS)
|
||||
state = {} # 1 = on the current path, 2 = finished
|
||||
reported = set()
|
||||
|
||||
def visit(step_id):
|
||||
state[step_id] = 1
|
||||
for target in successors[step_id]:
|
||||
if state.get(target) == 1 and (step_id, target) not in reported:
|
||||
reported.add((step_id, target))
|
||||
issues.append(issue('warning', 'loop', 'Loop back to "%s", capped at %d runs per step' % (target, limit), step_id))
|
||||
elif target not in state:
|
||||
visit(target)
|
||||
state[step_id] = 2
|
||||
|
||||
visit(graph['start'])
|
||||
|
||||
|
||||
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
|
||||
# EXECUTION #
|
||||
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
|
||||
|
||||
class Fire(object):
|
||||
|
||||
""" A workload that the scheduler has decided to create """
|
||||
|
||||
def __init__(self, step_key, kind, payload, via=''):
|
||||
self.step_key = step_key
|
||||
self.kind = kind
|
||||
self.payload = payload
|
||||
self.via = via # The outcome that led here, or '' for the start
|
||||
|
||||
def __repr__(self):
|
||||
return 'Fire(%s, %s, via=%r)' % (self.step_key, self.kind, self.via)
|
||||
|
||||
class Plan(object):
|
||||
|
||||
def __init__(self):
|
||||
self.fires = [] # Fire objects, to create
|
||||
self.notes = [] # Human readable reasons for anything skipped
|
||||
|
||||
def build_payload(step, overrides=None):
|
||||
|
||||
""" Final form fields for a step, as strings, exactly like a form post """
|
||||
|
||||
payload = dict(step['payload'])
|
||||
payload.update(overrides or {})
|
||||
return { str(key) : str(value) for key, value in payload.items() }
|
||||
|
||||
def initial_fire(graph):
|
||||
|
||||
start = graph['start']
|
||||
step = graph['steps'][start]
|
||||
return Fire(start, step['kind'], build_payload(step))
|
||||
|
||||
def plan_next(graph, step_key, outcome, visits, fired):
|
||||
|
||||
""" Decide what follows a step that just ended with the given outcome.
|
||||
|
||||
visits : { step_key : how many times that step was already created }
|
||||
fired : how many workloads this run has already created in total """
|
||||
|
||||
assert outcome in OUTCOMES
|
||||
|
||||
max_visits = graph.get('max_visits', DEFAULT_MAX_VISITS)
|
||||
max_steps = graph.get('max_steps' , DEFAULT_MAX_STEPS )
|
||||
|
||||
plan, planned = Plan(), {}
|
||||
|
||||
matching = [
|
||||
edge for edge in graph.get('edges', [])
|
||||
if edge['from'] == step_key and edge['on'] in (outcome, 'any')
|
||||
]
|
||||
|
||||
if not matching:
|
||||
plan.notes.append('Pipeline ended after "%s" (%s): no edge for this outcome' % (step_key, outcome))
|
||||
|
||||
for edge in matching:
|
||||
|
||||
target = edge['to']
|
||||
if target is None:
|
||||
plan.notes.append('Pipeline ended after "%s" (%s)' % (step_key, outcome))
|
||||
continue
|
||||
|
||||
if target in planned:
|
||||
plan.notes.append('"%s" was already queued by another edge' % (target))
|
||||
continue
|
||||
|
||||
if fired + len(plan.fires) >= max_steps:
|
||||
plan.notes.append('Not starting "%s": reached the limit of %d workloads' % (target, max_steps))
|
||||
continue
|
||||
|
||||
if visits.get(target, 0) >= max_visits:
|
||||
plan.notes.append('Not starting "%s": reached the limit of %d runs' % (target, max_visits))
|
||||
continue
|
||||
|
||||
step = graph['steps'][target]
|
||||
plan.fires.append(Fire(target, step['kind'], build_payload(step, edge.get('set')), outcome))
|
||||
planned[target] = True
|
||||
|
||||
return plan
|
||||
|
||||
def followed_edges(graph, hops):
|
||||
|
||||
""" Indices of the edges that a run actually went along, so that they can be
|
||||
shown apart from the ones it did not.
|
||||
|
||||
hops : [ ( step that ended, step that it started, how it ended ) ] """
|
||||
|
||||
taken = set()
|
||||
|
||||
for source, target, outcome in hops:
|
||||
for index, edge in enumerate(graph.get('edges', [])):
|
||||
if edge['from'] == source and edge['to'] == target and edge['on'] in (outcome, 'any'):
|
||||
taken.add(index)
|
||||
|
||||
return taken
|
||||
|
||||
def classify_outcome(finished, deleted, passed, failed, test_mode, games, spsa=None):
|
||||
|
||||
""" One of OUTCOMES for a workload that is over, or None while it is not """
|
||||
|
||||
if finished:
|
||||
|
||||
if passed: return 'passed'
|
||||
if failed: return 'failed'
|
||||
|
||||
# A tune never passes or fails. Running all of its iterations is success
|
||||
if test_mode == 'SPSA' and spsa:
|
||||
target = 2 * spsa.get('pairs_per', 0) * spsa.get('iterations', 0)
|
||||
if target > 0 and games >= target:
|
||||
return 'passed'
|
||||
|
||||
return 'stopped' # Stopped by hand, or by a bad bench
|
||||
|
||||
return 'stopped' if deleted else None
|
||||
|
||||
def run_status(statuses):
|
||||
|
||||
""" RUNNING while anything is in flight, else ERROR if anything could not
|
||||
be created, else COMPLETED """
|
||||
|
||||
if any(status in ACTIVE_STATUSES for status in statuses): return 'RUNNING'
|
||||
if any(status == 'ERROR' for status in statuses): return 'ERROR'
|
||||
return 'COMPLETED'
|
||||
@@ -0,0 +1,426 @@
|
||||
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
|
||||
# #
|
||||
# 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/>. #
|
||||
# #
|
||||
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
|
||||
|
||||
|
||||
|
||||
# Draws a Pipeline graph ( see pipeline_graph.py ) as an inline SVG. Like the
|
||||
# graph module, this is pure Python: no Django, no database. It never reads the
|
||||
# page it ends up on, so it can be tested on its own.
|
||||
#
|
||||
# The layout is layered, left to right. A step sits one column to the right of
|
||||
# the furthest step that leads into it. Edges that loop back to an earlier step
|
||||
# are drawn underneath the nodes, so that the main flow stays readable.
|
||||
#
|
||||
# Every piece of text in the output may come from a person ( step names, setting
|
||||
# values ), so all of it is escaped here, and only here. The result is a finished
|
||||
# string that a template may mark as safe.
|
||||
|
||||
import html
|
||||
|
||||
NODE_W = 196
|
||||
NODE_H = 84
|
||||
GAP_X = 112 # The least that is left between two columns
|
||||
GAP_Y = 34
|
||||
PAD = 36
|
||||
RADIUS = 2 # The corner radius of the theme ( --radius ). Sharp, and never more
|
||||
LOOP_DEPTH = 34 # How far below the nodes the first looping edge dips
|
||||
LOOP_STEP = 16 # How much further every other looping edge runs
|
||||
STUB = 34 # How far the stub of an edge that leads nowhere reaches past its label
|
||||
NAME_LIMIT = 24 # Characters of a step name that fit on the first line of a step
|
||||
|
||||
STATUSES = ('queued', 'launching', 'running', 'passed', 'failed', 'stopped', 'error')
|
||||
CONDITIONS = ('passed', 'failed', 'stopped', 'any')
|
||||
|
||||
def edge_label(condition, changes):
|
||||
|
||||
""" What is written on an edge: when it is followed, and what it changes """
|
||||
|
||||
condition = condition if condition in CONDITIONS else 'any'
|
||||
label = condition
|
||||
|
||||
if changes:
|
||||
label += ' (%d change%s)' % (len(changes), '' if len(changes) == 1 else 's')
|
||||
|
||||
return label
|
||||
|
||||
def label_width(label):
|
||||
return len(label) * 6.6 + 18
|
||||
|
||||
def esc(text):
|
||||
return html.escape(str(text), quote=True)
|
||||
|
||||
def clip(text, limit):
|
||||
text = str(text)
|
||||
return text if len(text) <= limit else text[:limit - 1] + '\u2026'
|
||||
|
||||
|
||||
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
|
||||
# LAYOUT #
|
||||
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
|
||||
|
||||
def _walk(graph):
|
||||
|
||||
""" Splits the edges into forward and back edges, using a depth first walk
|
||||
from the start. Returns ( order the steps were met in, back edge indices ) """
|
||||
|
||||
steps, edges = graph['steps'], graph.get('edges', [])
|
||||
outgoing = { step_id : [] for step_id in steps }
|
||||
|
||||
for index, edge in enumerate(edges):
|
||||
if edge.get('from') in outgoing and edge.get('to') in steps:
|
||||
outgoing[edge['from']].append((index, edge['to']))
|
||||
|
||||
state, order, back = {}, [], set()
|
||||
|
||||
def visit(step_id):
|
||||
state[step_id] = 1
|
||||
order.append(step_id)
|
||||
for index, target in outgoing[step_id]:
|
||||
if state.get(target) == 1:
|
||||
back.add(index) # Leads to a step that is still being walked: a loop
|
||||
elif target not in state:
|
||||
visit(target)
|
||||
state[step_id] = 2
|
||||
|
||||
if graph.get('start') in steps:
|
||||
visit(graph['start'])
|
||||
|
||||
return order, back
|
||||
|
||||
def layout(graph):
|
||||
|
||||
""" Positions of every step and edge, in SVG units """
|
||||
|
||||
steps, edges = graph['steps'], graph.get('edges', [])
|
||||
order, back = _walk(graph)
|
||||
reachable = set(order)
|
||||
|
||||
# A step is one column right of the furthest step leading into it. Steps are
|
||||
# taken in reverse finishing order, which is a valid order for the forward edges
|
||||
forward = [(e['from'], e['to']) for i, e in enumerate(edges)
|
||||
if i not in back and e.get('to') in steps and e.get('from') in reachable]
|
||||
|
||||
layer = { step_id : 0 for step_id in order }
|
||||
for _ in range(len(order)):
|
||||
changed = False
|
||||
for source, target in forward:
|
||||
if layer[target] < layer[source] + 1:
|
||||
layer[target] = layer[source] + 1
|
||||
changed = True
|
||||
if not changed:
|
||||
break
|
||||
|
||||
# Steps that can never start get a column of their own, at the end
|
||||
orphans = [step_id for step_id in steps if step_id not in reachable]
|
||||
if orphans:
|
||||
last = max(layer.values(), default=-1) + 1
|
||||
for step_id in orphans:
|
||||
layer[step_id] = last
|
||||
|
||||
columns = {}
|
||||
for step_id in list(order) + orphans:
|
||||
columns.setdefault(layer[step_id], []).append(step_id)
|
||||
|
||||
# Order inside a column: by the average row of whatever leads in
|
||||
row = {}
|
||||
for number in sorted(columns):
|
||||
members = columns[number]
|
||||
if number > 0:
|
||||
def average(step_id):
|
||||
rows = [row[s] for s, t in forward if t == step_id and s in row]
|
||||
return sum(rows) / len(rows) if rows else float('inf')
|
||||
|
||||
met = { step_id : position for position, step_id in enumerate(members) }
|
||||
members.sort(key=lambda step_id: (average(step_id), met[step_id]))
|
||||
for position, step_id in enumerate(members):
|
||||
row[step_id] = position
|
||||
|
||||
tallest = max((len(members) for members in columns.values()), default=1)
|
||||
back_count = len(back)
|
||||
|
||||
# Edges that skip over a column run in a lane above the steps in between, so
|
||||
# that they never cut through one. Those lanes need room above everything
|
||||
skipping = [i for i, e in enumerate(edges)
|
||||
if i not in back and e.get('to') in steps and e.get('from') in reachable
|
||||
and layer[e['to']] - layer[e['from']] > 1]
|
||||
headroom = (20 + 14 * len(skipping)) if skipping else 0
|
||||
|
||||
# The gap after a column is wide enough for the widest label that sits in it
|
||||
gap_after = { number : GAP_X for number in columns }
|
||||
for index, edge in enumerate(edges):
|
||||
if index not in back and edge.get('to') in steps and edge.get('from') in reachable \
|
||||
and layer[edge['to']] - layer[edge['from']] == 1:
|
||||
width = label_width(edge_label(edge.get('on'), edge.get('set') or {})) + 28
|
||||
gap_after[layer[edge['from']]] = max(gap_after[layer[edge['from']]], width)
|
||||
|
||||
left = {}
|
||||
for number in sorted(columns):
|
||||
left[number] = PAD if number == min(columns) else left[number - 1] + NODE_W + gap_after[number - 1]
|
||||
|
||||
nodes = {}
|
||||
for number, members in columns.items():
|
||||
shift = (tallest - len(members)) * (NODE_H + GAP_Y) / 2
|
||||
for position, step_id in enumerate(members):
|
||||
nodes[step_id] = {
|
||||
'id' : step_id,
|
||||
'layer' : number,
|
||||
'row' : position,
|
||||
'x' : left[number],
|
||||
'y' : PAD + headroom + shift + position * (NODE_H + GAP_Y),
|
||||
'w' : NODE_W,
|
||||
'h' : NODE_H,
|
||||
'reachable' : step_id in reachable,
|
||||
}
|
||||
|
||||
# Ports: edges leaving or entering the same side of a step are spread out
|
||||
leaving, entering = {}, {}
|
||||
for index, edge in enumerate(edges):
|
||||
if index in back or edge.get('from') not in nodes:
|
||||
continue
|
||||
leaving.setdefault(edge['from'], []).append(index)
|
||||
if edge.get('to') in nodes:
|
||||
entering.setdefault(edge['to'], []).append(index)
|
||||
|
||||
def port(table, step_id, index):
|
||||
indices = table[step_id]
|
||||
return nodes[step_id]['y'] + NODE_H * (indices.index(index) + 1) / (len(indices) + 1)
|
||||
|
||||
drawn, loops_seen = [], 0
|
||||
lowest = max((n['y'] + NODE_H for n in nodes.values()), default=0)
|
||||
|
||||
for index, edge in enumerate(edges):
|
||||
|
||||
source, target = edge.get('from'), edge.get('to')
|
||||
if source not in nodes or (target is not None and target not in nodes):
|
||||
continue
|
||||
|
||||
item = {
|
||||
'index' : index, 'source' : source, 'target' : target,
|
||||
'on' : edge.get('on'), 'back' : index in back,
|
||||
'end' : target is None, 'changes' : dict(edge.get('set') or {}),
|
||||
}
|
||||
|
||||
s = nodes[source]
|
||||
|
||||
if index in back:
|
||||
|
||||
# Under every step, so that a loop never runs through one
|
||||
t = nodes[target]
|
||||
lane = lowest + LOOP_DEPTH + LOOP_STEP * loops_seen
|
||||
loops_seen += 1
|
||||
|
||||
if source == target:
|
||||
x1, x2 = s['x'] + NODE_W * 0.35, s['x'] + NODE_W * 0.65
|
||||
else:
|
||||
x1, x2 = s['x'] + NODE_W * 0.5, t['x'] + NODE_W * 0.5
|
||||
|
||||
y1, y2 = s['y'] + NODE_H, t['y'] + NODE_H
|
||||
pull = (8 * lane - y1 - y2) / 6 # Puts the middle of the curve on the lane
|
||||
item['path'] = 'M%.1f %.1f C%.1f %.1f %.1f %.1f %.1f %.1f' % (x1, y1, x1, pull, x2, pull, x2, y2)
|
||||
item['lx'], item['ly'] = (x1 + x2) / 2, lane
|
||||
|
||||
elif target is None:
|
||||
|
||||
width = label_width(edge_label(edge.get('on'), item['changes']))
|
||||
length = width + STUB
|
||||
x1, y1 = s['x'] + NODE_W, port(leaving, source, index)
|
||||
x2 = x1 + length
|
||||
item['path'] = 'M%.1f %.1f L%.1f %.1f' % (x1, y1, x2, y1)
|
||||
item['lx'], item['ly'] = x1 + width / 2 + 8, y1
|
||||
item['ex'], item['ey'] = x2, y1
|
||||
item['length'] = length
|
||||
|
||||
elif index in skipping:
|
||||
|
||||
# Out into the gap, up to a lane above the steps in between, along it, and down again
|
||||
t = nodes[target]
|
||||
x1, y1 = s['x'] + NODE_W, port(leaving, source, index)
|
||||
x2, y2 = t['x'], port(entering, target, index)
|
||||
between = [n['y'] for n in nodes.values() if s['layer'] < n['layer'] < t['layer']]
|
||||
lane = min(between) - 18 - 14 * skipping.index(index)
|
||||
out_of = gap_after[s['layer']] # The gap that it leaves through
|
||||
into = gap_after[t['layer'] - 1] # And the one that it arrives through
|
||||
|
||||
item['path'] = 'M%.1f %.1f C%.1f %.1f %.1f %.1f %.1f %.1f L%.1f %.1f C%.1f %.1f %.1f %.1f %.1f %.1f' % (
|
||||
x1, y1, x1 + out_of * 0.6, y1, x1 + out_of * 0.6, lane, x1 + out_of, lane,
|
||||
x2 - into, lane,
|
||||
x2 - into * 0.6, lane, x2 - into * 0.6, y2, x2, y2)
|
||||
item['lx'], item['ly'] = (x1 + x2) / 2, lane
|
||||
|
||||
else:
|
||||
|
||||
t = nodes[target]
|
||||
x1, y1 = s['x'] + NODE_W, port(leaving, source, index)
|
||||
x2, y2 = t['x'], port(entering, target, index)
|
||||
reach = max(36.0, (x2 - x1) / 2)
|
||||
item['path'] = 'M%.1f %.1f C%.1f %.1f %.1f %.1f %.1f %.1f' % (
|
||||
x1, y1, x1 + reach, y1, x2 - reach, y2, x2, y2)
|
||||
item['lx'], item['ly'] = (x1 + x2) / 2, (y1 + y2) / 2
|
||||
|
||||
drawn.append(item)
|
||||
|
||||
right = max((n['x'] + NODE_W for n in nodes.values()), default=0)
|
||||
right += max((item['length'] for item in drawn if item['end']), default=0)
|
||||
|
||||
dip = (LOOP_DEPTH + LOOP_STEP * max(back_count - 1, 0) + 28) if back_count else 0
|
||||
|
||||
return {
|
||||
'width' : right + PAD,
|
||||
'height' : PAD * 2 + headroom + tallest * NODE_H + (tallest - 1) * GAP_Y + dip,
|
||||
'nodes' : nodes,
|
||||
'edges' : drawn,
|
||||
}
|
||||
|
||||
|
||||
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
|
||||
# DRAWING #
|
||||
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
|
||||
|
||||
def step_summary(step):
|
||||
|
||||
""" Two short facts about what a step runs: what it does, and how fast """
|
||||
|
||||
payload, kind = step.get('payload') or {}, step.get('kind')
|
||||
|
||||
if kind == 'TEST':
|
||||
if str(payload.get('test_mode')) == 'GAMES':
|
||||
what = '%s games' % (payload.get('test_max_games', '?'))
|
||||
else:
|
||||
what = 'SPRT %s' % (payload.get('test_bounds', ''))
|
||||
return what.strip(), str(payload.get('dev_time_control', ''))
|
||||
|
||||
if kind == 'TUNE':
|
||||
return 'SPSA, %s iterations' % (payload.get('spsa_iterations', '?')), str(payload.get('dev_time_control', ''))
|
||||
|
||||
if kind == 'DATAGEN':
|
||||
return '%s games' % (payload.get('datagen_max_games', '?')), str(payload.get('dev_time_control', ''))
|
||||
|
||||
return '', ''
|
||||
|
||||
def _safe_link(url):
|
||||
|
||||
# Links come from our own views, and are always paths on this site
|
||||
url = str(url or '')
|
||||
return url if url.startswith('/') and not url.startswith('//') else ''
|
||||
|
||||
def render_svg(graph, geometry=None, states=None, taken=None):
|
||||
|
||||
""" states : { step_id : { 'status' : 'running', 'runs' : 2, 'url' : '/test/9/' } }
|
||||
taken : set of edge indices that a run actually followed. When given,
|
||||
every edge that was not followed is drawn quietly. """
|
||||
|
||||
geometry = geometry or layout(graph)
|
||||
states = states or {}
|
||||
steps = graph['steps']
|
||||
|
||||
out = []
|
||||
out.append(
|
||||
'<svg class="pl-graph" xmlns="http://www.w3.org/2000/svg" role="group" '
|
||||
'aria-label="Pipeline flow" viewBox="0 0 %d %d" width="%d" height="%d">' % (
|
||||
geometry['width'], geometry['height'], geometry['width'], geometry['height']))
|
||||
|
||||
out.append('<defs>')
|
||||
for condition in CONDITIONS:
|
||||
out.append(
|
||||
'<marker id="pl-arrow-%s" viewBox="0 0 10 10" refX="9" refY="5" markerUnits="userSpaceOnUse" '
|
||||
'markerWidth="11" markerHeight="11" orient="auto"><path class="pl-arrow pl-c-%s" d="M0 0L10 5L0 10z"/></marker>' % (
|
||||
condition, condition))
|
||||
out.append('</defs>')
|
||||
|
||||
for item in geometry['edges']:
|
||||
|
||||
condition = item['on'] if item['on'] in CONDITIONS else 'any'
|
||||
classes = ['pl-edge', 'pl-c-' + condition]
|
||||
|
||||
if taken is not None:
|
||||
classes.append('pl-taken' if item['index'] in taken else 'pl-idle')
|
||||
if item['back']:
|
||||
classes.append('pl-back')
|
||||
|
||||
label = edge_label(condition, item['changes'])
|
||||
width = label_width(label)
|
||||
notes = []
|
||||
if item['changes']:
|
||||
notes = ['Settings changed when this is followed:'] + [
|
||||
'%s = %s' % (k, v) for k, v in sorted(item['changes'].items())]
|
||||
|
||||
out.append('<g class="%s" data-edge="%d">' % (' '.join(classes), item['index']))
|
||||
out.append('<path class="pl-line" d="%s" marker-end="url(#pl-arrow-%s)"/>' % (item['path'], condition))
|
||||
|
||||
if item['end']:
|
||||
out.append('<circle class="pl-end" cx="%.1f" cy="%.1f" r="4"/>' % (item['ex'], item['ey']))
|
||||
|
||||
out.append('<g class="pl-label">')
|
||||
if notes:
|
||||
out.append('<title>%s</title>' % (esc('\n'.join(notes))))
|
||||
out.append('<rect x="%.1f" y="%.1f" width="%.1f" height="20" rx="%d"/>' % (
|
||||
item['lx'] - width / 2, item['ly'] - 10, width, RADIUS))
|
||||
out.append('<text x="%.1f" y="%.1f" text-anchor="middle">%s</text>' % (
|
||||
item['lx'], item['ly'] + 4, esc(label)))
|
||||
out.append('</g></g>')
|
||||
|
||||
for step_id, node in geometry['nodes'].items():
|
||||
|
||||
step = steps[step_id]
|
||||
state = states.get(step_id) or {}
|
||||
status = state.get('status')
|
||||
status = status.lower() if isinstance(status, str) and status.lower() in STATUSES else 'idle'
|
||||
what, speed = step_summary(step)
|
||||
|
||||
classes = ['pl-node', 'pl-s-' + status]
|
||||
if step_id == graph.get('start'):
|
||||
classes.append('pl-start')
|
||||
if not node['reachable']:
|
||||
classes.append('pl-unreachable')
|
||||
|
||||
x, y = node['x'], node['y']
|
||||
name = step.get('name') or step_id
|
||||
runs = state.get('runs') or 0
|
||||
spoken = '%s: %s' % (name, status if status != 'idle' else ('never starts' if not node['reachable'] else 'not run'))
|
||||
if runs > 1:
|
||||
spoken += ', %d runs' % (runs)
|
||||
|
||||
link = _safe_link(state.get('url'))
|
||||
if link:
|
||||
out.append('<a href="%s">' % (esc(link)))
|
||||
|
||||
out.append('<g class="%s" data-step="%s">' % (' '.join(classes), esc(step_id)))
|
||||
out.append('<title>%s</title>' % (esc(spoken)))
|
||||
out.append('<rect class="pl-box" x="%.1f" y="%.1f" width="%d" height="%d" rx="%d"/>' % (x, y, NODE_W, NODE_H, RADIUS))
|
||||
|
||||
if step_id == graph.get('start'):
|
||||
out.append('<path class="pl-play" d="M%.1f %.1f L%.1f %.1f L%.1f %.1f z"/>' % (
|
||||
x - 20, y + NODE_H / 2 - 7, x - 8, y + NODE_H / 2, x - 20, y + NODE_H / 2 + 7))
|
||||
|
||||
out.append('<text class="pl-name" x="%.1f" y="%.1f">%s</text>' % (x + 14, y + 27, esc(clip(name, NAME_LIMIT))))
|
||||
out.append('<text class="pl-what" x="%.1f" y="%.1f">%s</text>' % (x + 14, y + 49, esc(clip(what, 24))))
|
||||
out.append('<text class="pl-speed" x="%.1f" y="%.1f">%s</text>' % (x + 14, y + 70, esc(clip(speed, 12))))
|
||||
|
||||
if status != 'idle':
|
||||
tag = status + (' x%d' % (runs) if runs > 1 else '')
|
||||
out.append('<text class="pl-status" x="%.1f" y="%.1f" text-anchor="end">%s</text>' % (
|
||||
x + NODE_W - 14, y + 70, esc(tag)))
|
||||
|
||||
out.append('</g>')
|
||||
if link:
|
||||
out.append('</a>')
|
||||
|
||||
out.append('</svg>')
|
||||
return ''.join(out)
|
||||
@@ -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')
|
||||
@@ -0,0 +1,395 @@
|
||||
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
|
||||
# #
|
||||
# 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 scheduler: starts workloads, and decides what to start next once
|
||||
# a workload ends. All of the decision making lives in OpenBench/pipeline_graph.py
|
||||
# and is free of Django. This module only does the bookkeeping around it.
|
||||
#
|
||||
# How a run moves along:
|
||||
#
|
||||
# start_pipeline() queues the starting step, then launches it
|
||||
# workload_finished() is called whenever a workload is over ( passed,
|
||||
# failed, stopped, deleted ). Resolves its step,
|
||||
# queues whatever the graph says comes next
|
||||
# launch_step() creates the actual workload for a queued step,
|
||||
# through the same code that the web forms use
|
||||
# catch_up() safety net for anything the above missed
|
||||
#
|
||||
# Deciding happens inside a short transaction. Creating a workload talks to the
|
||||
# Github API, so that always happens outside of any transaction, in order to not
|
||||
# hold the database ( SQLite locks all of it ) while waiting on the network.
|
||||
|
||||
import copy
|
||||
import sys
|
||||
import threading
|
||||
import traceback
|
||||
|
||||
from collections import Counter
|
||||
from datetime import timedelta
|
||||
|
||||
from django.contrib.auth.models import User
|
||||
from django.db import connections, transaction
|
||||
from django.utils import timezone
|
||||
|
||||
import OpenBench.pipeline_graph as graphs
|
||||
|
||||
from OpenBench.models import LogEvent, Pipeline, PipelineRun, Profile, StepRun, Test
|
||||
|
||||
STALE_LAUNCH_SECONDS = 300 # A LAUNCHING step older than this was abandoned
|
||||
QUEUED_GRACE_SECONDS = 30 # Give the hook this long, before catch_up() steps in
|
||||
MAX_NOTES = 50
|
||||
|
||||
class PipelineRequest(object):
|
||||
|
||||
""" Stands in for a Django request, so that workloads made by a Pipeline are
|
||||
verified and created by exactly the code that the web forms use """
|
||||
|
||||
def __init__(self, user, post):
|
||||
self.user = user
|
||||
self.POST = post
|
||||
self.FILES = {}
|
||||
self.method = 'POST'
|
||||
|
||||
def _log(author, summary, test_id=0):
|
||||
LogEvent.objects.create(author=author, summary=summary[:128], log_file='', test_id=test_id)
|
||||
|
||||
def _add_notes(run, notes):
|
||||
run.notes = (list(run.notes or []) + list(notes))[-MAX_NOTES:]
|
||||
|
||||
def _queue(run, fire, parent):
|
||||
|
||||
# Caller holds the lock on run, and saves it
|
||||
run.fired += 1
|
||||
|
||||
return StepRun.objects.create(
|
||||
run=run, parent=parent, step_key=fire.step_key,
|
||||
via=fire.via, kind=fire.kind, payload=fire.payload)
|
||||
|
||||
def _refresh_run(run, halted=False):
|
||||
|
||||
# Caller holds the lock on run
|
||||
status = graphs.run_status(list(run.steps.values_list('status', flat=True)))
|
||||
|
||||
if (halted and status == 'COMPLETED') or run.status == 'CANCELLED':
|
||||
status = 'CANCELLED' # Cancelled by hand, or by disabling the Pipeline: it stays that way
|
||||
|
||||
run.status = status
|
||||
run.save()
|
||||
|
||||
|
||||
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
|
||||
# STARTING #
|
||||
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
|
||||
|
||||
def start_pipeline(pipeline, starter=None):
|
||||
|
||||
""" Returns ( run, issues ). The run is None if the Pipeline cannot run """
|
||||
|
||||
issues = graphs.validate_graph(pipeline.graph)
|
||||
|
||||
if not pipeline.enabled or pipeline.deleted:
|
||||
issues.append(graphs.issue('error', 'pipeline.disabled', 'The pipeline is disabled'))
|
||||
|
||||
if graphs.has_errors(issues):
|
||||
return None, issues
|
||||
|
||||
with transaction.atomic():
|
||||
run = PipelineRun.objects.create(
|
||||
pipeline=pipeline, graph=copy.deepcopy(pipeline.graph),
|
||||
starter=starter or pipeline.author)
|
||||
_queue(run, graphs.initial_fire(run.graph), None)
|
||||
run.save()
|
||||
|
||||
_log(run.starter, 'PIPELINE #%d RUN #%d STARTED' % (pipeline.id, run.id)) # By whoever pressed the button
|
||||
|
||||
launch_queued(run.id)
|
||||
return PipelineRun.objects.get(id=run.id), issues
|
||||
|
||||
|
||||
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
|
||||
# LAUNCHING #
|
||||
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
|
||||
|
||||
def launch_queued(run_id):
|
||||
for step_id in StepRun.objects.filter(run_id=run_id, status='QUEUED').order_by('id').values_list('id', flat=True):
|
||||
launch_step(step_id)
|
||||
|
||||
def launch_step(step_id):
|
||||
|
||||
# Claim the step, so that the hook and catch_up() can never both create it
|
||||
claimed = StepRun.objects.filter(id=step_id, status='QUEUED').update(status='LAUNCHING', updated=timezone.now())
|
||||
if claimed != 1:
|
||||
return
|
||||
|
||||
step = StepRun.objects.get(id=step_id)
|
||||
pipeline = Pipeline.objects.get(id=step.run.pipeline_id)
|
||||
|
||||
try:
|
||||
workload, errors = _create_workload(step, pipeline)
|
||||
except Exception:
|
||||
traceback.print_exc(); sys.stdout.flush()
|
||||
workload, errors = None, ['Unexpected error while creating the workload']
|
||||
|
||||
failed = False
|
||||
|
||||
with transaction.atomic():
|
||||
|
||||
run = PipelineRun.objects.select_for_update().get(id=step.run_id)
|
||||
step = StepRun.objects.select_for_update().get(id=step_id)
|
||||
|
||||
if step.status != 'LAUNCHING':
|
||||
# The run was cancelled while this was being created. The step stays as
|
||||
# cancelling left it, but a workload that did get made is not forgotten
|
||||
if workload is not None:
|
||||
step.test_id = workload.id
|
||||
step.message = (step.message + '. Its workload was already being created')[:512]
|
||||
step.save()
|
||||
|
||||
elif errors:
|
||||
failed = True
|
||||
step.status = 'ERROR'
|
||||
step.message = ' / '.join(errors)[:512]
|
||||
step.resolved = timezone.now()
|
||||
step.save()
|
||||
_add_notes(run, ['Could not create "%s": %s' % (step.step_key, step.message)])
|
||||
|
||||
else:
|
||||
step.status = 'RUNNING'
|
||||
step.test_id = workload.id
|
||||
step.save()
|
||||
|
||||
_refresh_run(run, halted=not pipeline.enabled or pipeline.deleted)
|
||||
|
||||
if failed:
|
||||
_log(pipeline.author, 'PIPELINE #%d %s ERROR' % (pipeline.id, step.step_key))
|
||||
|
||||
def _create_workload(step, pipeline):
|
||||
|
||||
# Imported late: the workload modules depend on OpenBench.utils, which in
|
||||
# turn calls into this module when a workload ends. They must be entered by
|
||||
# way of OpenBench.views, like the web server does, or they import in circles
|
||||
import OpenBench.views
|
||||
|
||||
from OpenBench.config import OPENBENCH_CONFIG
|
||||
from OpenBench.workloads import create_workload as creation
|
||||
|
||||
user = User.objects.filter(username=pipeline.author).first()
|
||||
profile = Profile.objects.filter(user=user).first() if user else None
|
||||
|
||||
if not profile or not profile.enabled:
|
||||
return None, ['"%s" is not an enabled user' % (pipeline.author)]
|
||||
|
||||
creators = {
|
||||
'TEST' : creation.create_new_test,
|
||||
'TUNE' : creation.create_new_tune,
|
||||
'DATAGEN' : creation.create_new_datagen,
|
||||
}
|
||||
|
||||
workload, errors = creators[step.kind](PipelineRequest(user, dict(step.payload)))
|
||||
|
||||
if errors:
|
||||
return None, errors
|
||||
|
||||
# The same bookkeeping that create_workload() does after creating a workload
|
||||
summary = 'CREATE P=%d TP=%d' % (workload.priority, workload.throughput)
|
||||
_log(user.username, summary, workload.id)
|
||||
|
||||
if not OPENBENCH_CONFIG['use_cross_approval'] and profile.approver:
|
||||
workload.approved = True
|
||||
workload.save()
|
||||
|
||||
return workload, None
|
||||
|
||||
|
||||
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
|
||||
# LOOKING UP #
|
||||
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
|
||||
|
||||
def step_of(test_id):
|
||||
|
||||
""" Which step of which run made a workload, for showing on the page of that
|
||||
workload. None for the great majority of workloads, that no Pipeline made. """
|
||||
|
||||
step = StepRun.objects.select_related('run__pipeline', 'parent').filter(test_id=test_id).first()
|
||||
|
||||
if step is None:
|
||||
return None
|
||||
|
||||
names = (step.run.graph or {}).get('steps', {})
|
||||
name = lambda key: (names.get(key) or {}).get('name') or key
|
||||
|
||||
return {
|
||||
'name' : name(step.step_key),
|
||||
'pipeline' : step.run.pipeline.name,
|
||||
'run_id' : step.run_id,
|
||||
'after' : 'After %s %s' % (name(step.parent.step_key), step.via) if step.parent_id else '',
|
||||
}
|
||||
|
||||
|
||||
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
|
||||
# CANCELLING #
|
||||
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
|
||||
|
||||
def cancel_run(run_id, by):
|
||||
|
||||
""" Ends a run for good, so that nothing more starts from it. Whatever has not
|
||||
started yet is stopped. Workloads that are already running are left alone,
|
||||
since stopping a test is a decision for the page of that test. Returns
|
||||
whether there was a running run to cancel. """
|
||||
|
||||
with transaction.atomic():
|
||||
|
||||
run = PipelineRun.objects.select_for_update().filter(id=run_id).first()
|
||||
if run is None or run.status != 'RUNNING':
|
||||
return False
|
||||
|
||||
now = timezone.now()
|
||||
for step in StepRun.objects.select_for_update().filter(run=run, status__in=('QUEUED', 'LAUNCHING')):
|
||||
step.status = 'STOPPED'
|
||||
step.message = 'Run cancelled by %s' % (by)
|
||||
step.resolved = now
|
||||
step.save()
|
||||
|
||||
run.status = 'CANCELLED'
|
||||
_add_notes(run, ['Cancelled by %s' % (by)])
|
||||
run.save()
|
||||
|
||||
_log(by, 'PIPELINE #%d RUN #%d CANCELLED' % (run.pipeline_id, run.id))
|
||||
return True
|
||||
|
||||
|
||||
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
|
||||
# ADVANCING #
|
||||
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
|
||||
|
||||
def workload_finished(test_id, background=True):
|
||||
|
||||
""" Hook for everything that can end a workload. Safe to call for any
|
||||
workload, at any time, as many times as you like, and never raises.
|
||||
|
||||
Cheap for workloads that no Pipeline cares about, which is nearly all
|
||||
of them. Otherwise carries on in a thread, since creating the next
|
||||
workload needs the Github API, and the caller is often a Worker who
|
||||
should not be kept waiting for that. """
|
||||
|
||||
try:
|
||||
if not StepRun.objects.filter(test_id=test_id, status='RUNNING').exists():
|
||||
return
|
||||
except Exception:
|
||||
traceback.print_exc(); sys.stdout.flush()
|
||||
return
|
||||
|
||||
if not background:
|
||||
return _advance(test_id, guarded=True)
|
||||
|
||||
threading.Thread(target=_advance_in_thread, args=(test_id,), daemon=True).start()
|
||||
|
||||
def _advance_in_thread(test_id):
|
||||
try: _advance(test_id, guarded=True)
|
||||
finally: connections.close_all() # Threads own their database connections
|
||||
|
||||
def _advance(test_id, guarded=False):
|
||||
|
||||
if guarded:
|
||||
try: return _advance(test_id)
|
||||
except Exception:
|
||||
traceback.print_exc(); sys.stdout.flush()
|
||||
return
|
||||
|
||||
to_launch = []
|
||||
|
||||
with transaction.atomic():
|
||||
|
||||
step = StepRun.objects.select_for_update().filter(test_id=test_id, status='RUNNING').first()
|
||||
test = Test.objects.filter(id=test_id).first()
|
||||
|
||||
if step is None or test is None:
|
||||
return # Already handled, or nothing that we know of
|
||||
|
||||
outcome = graphs.classify_outcome(
|
||||
test.finished, test.deleted, test.passed, test.failed,
|
||||
test.test_mode, test.games, getattr(test, 'spsa', None))
|
||||
|
||||
if outcome is None:
|
||||
return # Still going
|
||||
|
||||
run = PipelineRun.objects.select_for_update().get(id=step.run_id)
|
||||
pipeline = Pipeline.objects.get(id=run.pipeline_id)
|
||||
halted = not pipeline.enabled or pipeline.deleted
|
||||
|
||||
step.status = outcome.upper()
|
||||
step.resolved = timezone.now()
|
||||
step.save()
|
||||
|
||||
_log(pipeline.author, 'PIPELINE #%d %s %s' % (pipeline.id, step.step_key, outcome.upper()), test_id)
|
||||
|
||||
if run.status != 'RUNNING':
|
||||
pass # Nothing may start from a run that is already over
|
||||
|
||||
elif halted:
|
||||
_add_notes(run, ['Pipeline is disabled, not carrying on after "%s"' % (step.step_key)])
|
||||
|
||||
else:
|
||||
visits = Counter(run.steps.values_list('step_key', flat=True))
|
||||
plan = graphs.plan_next(run.graph, step.step_key, outcome, visits, run.fired)
|
||||
|
||||
_add_notes(run, plan.notes)
|
||||
to_launch = [_queue(run, fire, step) for fire in plan.fires]
|
||||
|
||||
_refresh_run(run, halted)
|
||||
|
||||
for queued in to_launch:
|
||||
launch_step(queued.id)
|
||||
|
||||
|
||||
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
|
||||
# SAFETY NET #
|
||||
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
|
||||
|
||||
def catch_up():
|
||||
|
||||
""" Picks up whatever the hooks could not: the server was down when a
|
||||
workload ended, a thread died halfway, a launch was interrupted. Safe
|
||||
to run at any time, and as often as you like. Returns what it found. """
|
||||
|
||||
now = timezone.now()
|
||||
found = { 'relaunched' : 0, 'resolved' : 0 }
|
||||
|
||||
# A launch that started, but never reported back. Whether or not the
|
||||
# workload got created, there is no way to know here. A duplicate is much
|
||||
# better than a pipeline that silently stalls, so it gets queued again.
|
||||
stale = now - timedelta(seconds=STALE_LAUNCH_SECONDS)
|
||||
StepRun.objects.filter(status='LAUNCHING', test_id=0, updated__lt=stale).update(status='QUEUED')
|
||||
|
||||
waiting = now - timedelta(seconds=QUEUED_GRACE_SECONDS)
|
||||
for step_id in StepRun.objects.filter(status='QUEUED', updated__lt=waiting).order_by('id').values_list('id', flat=True):
|
||||
launch_step(step_id)
|
||||
found['relaunched'] += 1
|
||||
|
||||
# Workloads that are over, but whose Step was never told so
|
||||
running = StepRun.objects.filter(status='RUNNING', test_id__gt=0)
|
||||
for test_id in list(running.values_list('test_id', flat=True)):
|
||||
before = StepRun.objects.filter(test_id=test_id, status='RUNNING').exists()
|
||||
_advance(test_id, guarded=True)
|
||||
after = StepRun.objects.filter(test_id=test_id, status='RUNNING').exists()
|
||||
found['resolved'] += int(before and not after)
|
||||
|
||||
return found
|
||||
@@ -1,9 +1,5 @@
|
||||
function enforce_default_text(id, text) {
|
||||
|
||||
// `text` may be a list of accepted prefixes; the first one is the default.
|
||||
var prefixes = Array.isArray(text) ? text : [text];
|
||||
text = prefixes[0];
|
||||
|
||||
window.addEventListener('DOMContentLoaded', function() {
|
||||
|
||||
var field = document.getElementById(id);
|
||||
@@ -13,8 +9,7 @@ function enforce_default_text(id, text) {
|
||||
|
||||
field.addEventListener('input', function() {
|
||||
|
||||
// Accept any allowed prefix, and anything still being typed towards one
|
||||
if (prefixes.some(function(p) { return field.value.startsWith(p) || p.startsWith(field.value); }))
|
||||
if (field.value.startsWith(text) || field.value === text)
|
||||
return;
|
||||
|
||||
if (field.value.endsWith('/'))
|
||||
|
||||
@@ -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);
|
||||
|
||||
})();
|
||||
@@ -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) {
|
||||
|
||||
@@ -22,7 +22,6 @@ import html
|
||||
import json
|
||||
import re, django
|
||||
import OpenBench.config, OpenBench.utils, OpenBench.stats, OpenBench.models
|
||||
import OpenBench.git_hosts
|
||||
|
||||
from django.utils.safestring import mark_safe
|
||||
|
||||
@@ -54,17 +53,14 @@ def gitDiffLink(test):
|
||||
|
||||
if test.dev_engine in engines and engines[test.dev_engine]['private']:
|
||||
repo = OpenBench.config.OPENBENCH_CONFIG['engines'][test.dev_engine]['source']
|
||||
elif OpenBench.git_hosts.is_gitea(test.dev_repo):
|
||||
repo = test.dev_repo # Gitea sources point at this server's /giteaSource/
|
||||
else:
|
||||
repo = OpenBench.utils.path_join(*test.dev.source.split('/')[:-2])
|
||||
|
||||
if test.test_mode == 'SPSA':
|
||||
if OpenBench.git_hosts.is_gitea(repo):
|
||||
return OpenBench.utils.path_join(repo, 'commit', test.dev.sha)
|
||||
return OpenBench.utils.path_join(repo, 'compare', test.dev.sha[:8])
|
||||
|
||||
return OpenBench.git_hosts.compare_url(repo, test.base.sha[:8], test.dev.sha[:8])
|
||||
return OpenBench.utils.path_join(repo, 'compare',
|
||||
'{0}..{1}'.format( test.base.sha[:8], test.dev.sha[:8]))
|
||||
|
||||
def shortStatBlock(test):
|
||||
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,493 @@
|
||||
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
|
||||
# #
|
||||
# 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/>. #
|
||||
# #
|
||||
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
|
||||
|
||||
|
||||
# Run with: python3 manage.py test OpenBench
|
||||
#
|
||||
# Exercises the Pipeline scheduler against a real ( test ) database. Creating a
|
||||
# workload normally verifies it against the Github API, which is replaced here
|
||||
# by a stand-in that only saves the Test. Everything else is the real thing.
|
||||
|
||||
import unittest
|
||||
|
||||
from datetime import timedelta
|
||||
from unittest import mock
|
||||
|
||||
from django.contrib.auth.models import User
|
||||
from django.core.exceptions import ValidationError
|
||||
from django.test import TestCase
|
||||
from django.utils import timezone
|
||||
|
||||
import OpenBench.pipelines as pipelines
|
||||
|
||||
from OpenBench.models import Engine, LogEvent, Pipeline, PipelineRun, Profile, StepRun, Test
|
||||
|
||||
# Older Test models keep the SPSA settings in a field, newer ones in another table
|
||||
HAS_SPSA = any(field.name == 'spsa' for field in Test._meta.get_fields())
|
||||
|
||||
def payload(**changes):
|
||||
|
||||
data = {
|
||||
'dev_engine' : 'Stockfish', 'dev_repo' : 'https://github.com/o/r', 'dev_branch' : 'dev',
|
||||
'dev_network' : '', 'dev_options' : 'Threads=1 Hash=8', 'dev_time_control' : '8.0+0.08',
|
||||
'base_engine' : 'Stockfish', 'base_repo' : 'https://github.com/o/r', 'base_branch' : 'master',
|
||||
'base_network' : '', 'base_options' : 'Threads=1 Hash=8', 'base_time_control' : '8.0+0.08',
|
||||
'book_name' : 'UHO.epd', 'upload_pgns' : 'FALSE', 'priority' : '0', 'throughput' : '1000',
|
||||
'syzygy_wdl' : 'OPTIONAL', 'syzygy_adj' : 'OPTIONAL',
|
||||
'win_adj' : 'movecount=3 score=400', 'draw_adj' : 'movenumber=40 movecount=8 score=10',
|
||||
'workload_size' : '32', 'test_mode' : 'SPRT',
|
||||
'test_bounds' : '[0.00, 2.00]', 'test_confidence' : '[0.10, 0.10]',
|
||||
}
|
||||
|
||||
data.update(changes)
|
||||
return data
|
||||
|
||||
def step(name, kind='TEST', **changes):
|
||||
return { 'name' : name, 'kind' : kind, 'payload' : payload(**changes) }
|
||||
|
||||
def tune_step(name):
|
||||
|
||||
data = { k : v for k, v in payload().items() if not k.startswith('base_') }
|
||||
for key in ('workload_size', 'test_mode', 'test_bounds', 'test_confidence'): del data[key]
|
||||
|
||||
data.update({
|
||||
'spsa_alpha' : '0.602', 'spsa_gamma' : '0.101', 'spsa_A_ratio' : '0.1',
|
||||
'spsa_iterations' : '2', 'spsa_pairs_per' : '1',
|
||||
'spsa_reporting_type' : 'BULK', 'spsa_distribution_type' : 'SINGLE',
|
||||
'spsa_inputs' : 'Aspiration, int, 20, 5, 50, 4, 0.002' })
|
||||
|
||||
return { 'name' : name, 'kind' : 'TUNE', 'payload' : data }
|
||||
|
||||
def graph(**changes):
|
||||
|
||||
data = {
|
||||
'version' : 1, 'start' : 'stc',
|
||||
'steps' : { 'stc' : step('STC'), 'ltc' : step('LTC', dev_time_control='40.0+0.40'), 'retry' : step('Retry') },
|
||||
'edges' : [
|
||||
{ 'from' : 'stc', 'on' : 'passed', 'to' : 'ltc', 'set' : { 'priority' : '5' } },
|
||||
{ 'from' : 'stc', 'on' : 'failed', 'to' : 'retry' },
|
||||
],
|
||||
}
|
||||
|
||||
data.update(changes)
|
||||
return data
|
||||
|
||||
class FakeCreator(object):
|
||||
|
||||
""" Stands in for create_new_test / create_new_tune / create_new_datagen """
|
||||
|
||||
def __init__(self, errors=None, explode=False, mode='SPRT'):
|
||||
self.calls, self.errors, self.explode, self.mode = [], errors, explode, mode
|
||||
self.during = None # Called in the middle of creating, like a person clicking Cancel then
|
||||
|
||||
def __call__(self, request):
|
||||
|
||||
self.calls.append(request)
|
||||
if self.during: self.during()
|
||||
|
||||
if self.explode: raise RuntimeError('Github is down')
|
||||
if self.errors : return None, list(self.errors)
|
||||
|
||||
engine = Engine.objects.first()
|
||||
post = request.POST
|
||||
|
||||
extra = { 'spsa' : { 'pairs_per' : 1, 'iterations' : 2 } } if self.mode == 'SPSA' and HAS_SPSA else {}
|
||||
|
||||
test = Test.objects.create(
|
||||
author=request.user.username, book_name=post['book_name'],
|
||||
dev=engine, dev_repo=post['dev_repo'], dev_engine=post['dev_engine'],
|
||||
dev_options=post['dev_options'], dev_time_control=post['dev_time_control'],
|
||||
base=engine, base_repo=post.get('base_repo', ''), base_engine=post.get('base_engine', ''),
|
||||
base_options=post.get('base_options', ''), base_time_control=post.get('base_time_control', ''),
|
||||
priority=int(post['priority']), throughput=int(post['throughput']),
|
||||
test_mode=self.mode, **extra)
|
||||
|
||||
return test, None
|
||||
|
||||
class PipelineTestCase(TestCase):
|
||||
|
||||
def setUp(self):
|
||||
|
||||
self.engine = Engine.objects.create(name='dev', source='x', sha='0' * 40, bench=1)
|
||||
self.user = User.objects.create_user('alice', 'a@example.com', 'pw')
|
||||
self.profile = Profile.objects.create(user=self.user, enabled=True, approver=True)
|
||||
|
||||
self.creator = FakeCreator()
|
||||
patches = [
|
||||
mock.patch('OpenBench.workloads.create_workload.create_new_test' , self.creator),
|
||||
mock.patch('OpenBench.workloads.create_workload.create_new_tune' , self.creator),
|
||||
mock.patch('OpenBench.workloads.create_workload.create_new_datagen', self.creator),
|
||||
]
|
||||
|
||||
for patch in patches:
|
||||
patch.start(); self.addCleanup(patch.stop)
|
||||
|
||||
# Helpers
|
||||
|
||||
def pipeline(self, **changes):
|
||||
return Pipeline.objects.create(name='P', author='alice', graph=changes.pop('graph', graph()), **changes)
|
||||
|
||||
def start(self, **kwargs):
|
||||
run, issues = pipelines.start_pipeline(self.pipeline(**kwargs))
|
||||
self.assertIsNotNone(run, issues)
|
||||
return run
|
||||
|
||||
def steps(self, run):
|
||||
return { s.step_key : s for s in StepRun.objects.filter(run=run).order_by('id') }
|
||||
|
||||
def finish(self, step_run, passed=False, failed=False, deleted=False, finished=True):
|
||||
|
||||
test = Test.objects.get(id=step_run.test_id)
|
||||
test.finished, test.passed, test.failed, test.deleted = finished, passed, failed, deleted
|
||||
test.save()
|
||||
|
||||
pipelines.workload_finished(test.id, background=False)
|
||||
|
||||
def keys(self, run):
|
||||
return [s.step_key for s in StepRun.objects.filter(run=run).order_by('id')]
|
||||
|
||||
def status(self, run):
|
||||
return PipelineRun.objects.get(id=run.id).status
|
||||
|
||||
class StartingTests(PipelineTestCase):
|
||||
|
||||
def test_start_creates_the_first_workload(self):
|
||||
|
||||
run = self.start()
|
||||
first = self.steps(run)['stc']
|
||||
|
||||
self.assertEqual((first.status, run.status, run.fired), ('RUNNING', 'RUNNING', 1))
|
||||
self.assertTrue(Test.objects.filter(id=first.test_id, author='alice').exists())
|
||||
self.assertEqual(self.creator.calls[0].POST['dev_branch'], 'dev')
|
||||
|
||||
def test_invalid_graph_never_starts(self):
|
||||
|
||||
bad = graph(start='nope')
|
||||
run, issues = pipelines.start_pipeline(self.pipeline(graph=bad))
|
||||
|
||||
self.assertIsNone(run)
|
||||
self.assertEqual(PipelineRun.objects.count(), 0)
|
||||
self.assertTrue(any(i['code'] == 'start.missing' for i in issues))
|
||||
|
||||
def test_disabled_pipeline_never_starts(self):
|
||||
run, issues = pipelines.start_pipeline(self.pipeline(enabled=False))
|
||||
self.assertIsNone(run)
|
||||
|
||||
def test_invalid_graphs_cannot_be_saved_through_forms(self):
|
||||
with self.assertRaises(ValidationError):
|
||||
Pipeline(name='x', author='alice', graph={}).full_clean()
|
||||
|
||||
def test_run_works_from_a_snapshot(self):
|
||||
|
||||
pipeline = self.pipeline()
|
||||
run, _ = pipelines.start_pipeline(pipeline)
|
||||
|
||||
pipeline.graph['edges'] = []; pipeline.save()
|
||||
self.finish(self.steps(run)['stc'], passed=True)
|
||||
|
||||
self.assertEqual(self.keys(run), ['stc', 'ltc'])
|
||||
|
||||
class BranchingTests(PipelineTestCase):
|
||||
|
||||
def test_passed_starts_ltc_with_the_edge_overrides(self):
|
||||
|
||||
run = self.start()
|
||||
self.finish(self.steps(run)['stc'], passed=True)
|
||||
|
||||
steps = self.steps(run)
|
||||
self.assertEqual(self.keys(run), ['stc', 'ltc'])
|
||||
self.assertEqual((steps['stc'].status, steps['ltc'].status, steps['ltc'].via), ('PASSED', 'RUNNING', 'passed'))
|
||||
self.assertEqual(self.creator.calls[1].POST['dev_time_control'], '40.0+0.40')
|
||||
self.assertEqual(self.creator.calls[1].POST['priority'], '5')
|
||||
self.assertEqual(steps['ltc'].parent_id, steps['stc'].id)
|
||||
self.assertEqual(self.status(run), 'RUNNING')
|
||||
|
||||
def test_failed_starts_retry(self):
|
||||
|
||||
run = self.start()
|
||||
self.finish(self.steps(run)['stc'], failed=True)
|
||||
self.assertEqual(self.keys(run), ['stc', 'retry'])
|
||||
|
||||
def test_a_run_completes_when_nothing_is_left(self):
|
||||
|
||||
run = self.start()
|
||||
self.finish(self.steps(run)['stc'], passed=True)
|
||||
self.finish(self.steps(run)['ltc'], passed=True)
|
||||
|
||||
self.assertEqual(self.status(run), 'COMPLETED')
|
||||
self.assertEqual(PipelineRun.objects.get(id=run.id).fired, 2)
|
||||
|
||||
def test_stopped_by_hand_has_no_edge_and_ends_the_run(self):
|
||||
|
||||
run = self.start()
|
||||
self.finish(self.steps(run)['stc'])
|
||||
|
||||
self.assertEqual(self.steps(run)['stc'].status, 'STOPPED')
|
||||
self.assertEqual(self.status(run), 'COMPLETED')
|
||||
self.assertIn('no edge', ' '.join(PipelineRun.objects.get(id=run.id).notes))
|
||||
|
||||
def test_deleting_a_running_workload_counts_as_stopped(self):
|
||||
|
||||
run = self.start()
|
||||
self.finish(self.steps(run)['stc'], deleted=True, finished=False)
|
||||
self.assertEqual(self.steps(run)['stc'].status, 'STOPPED')
|
||||
|
||||
def test_a_workload_that_is_still_running_changes_nothing(self):
|
||||
|
||||
run = self.start()
|
||||
self.finish(self.steps(run)['stc'], finished=False)
|
||||
|
||||
self.assertEqual(self.steps(run)['stc'].status, 'RUNNING')
|
||||
self.assertEqual(self.keys(run), ['stc'])
|
||||
|
||||
def test_fan_out_starts_every_branch(self):
|
||||
|
||||
both = graph(); both['edges'].append({ 'from' : 'stc', 'on' : 'passed', 'to' : 'retry' })
|
||||
run = self.start(graph=both)
|
||||
self.finish(self.steps(run)['stc'], passed=True)
|
||||
|
||||
self.assertEqual(sorted(self.keys(run)), ['ltc', 'retry', 'stc'])
|
||||
self.finish(self.steps(run)['ltc'], passed=True)
|
||||
self.assertEqual(self.status(run), 'RUNNING') # retry is still going
|
||||
|
||||
self.finish(self.steps(run)['retry'], failed=True)
|
||||
self.assertEqual(self.status(run), 'COMPLETED')
|
||||
|
||||
@unittest.skipUnless(HAS_SPSA, 'Test has no spsa field')
|
||||
def test_completed_tune_passes(self):
|
||||
|
||||
tune = graph(steps={ 'tune' : tune_step('Tune'), 'ltc' : step('LTC') }, start='tune',
|
||||
edges=[{ 'from' : 'tune', 'on' : 'passed', 'to' : 'ltc' }])
|
||||
|
||||
self.creator.mode = 'SPSA'
|
||||
run = self.start(graph=tune)
|
||||
|
||||
test = Test.objects.get(id=self.steps(run)['tune'].test_id)
|
||||
test.games, test.finished = 4, True # 2 * pairs_per * iterations
|
||||
test.save()
|
||||
pipelines.workload_finished(test.id, background=False)
|
||||
|
||||
self.assertEqual(self.steps(run)['tune'].status, 'PASSED')
|
||||
self.assertEqual(self.keys(run), ['tune', 'ltc'])
|
||||
|
||||
class SafetyTests(PipelineTestCase):
|
||||
|
||||
def test_the_hook_is_idempotent(self):
|
||||
|
||||
run = self.start()
|
||||
stc = self.steps(run)['stc']
|
||||
|
||||
self.finish(stc, passed=True)
|
||||
pipelines.workload_finished(stc.test_id, background=False)
|
||||
pipelines.workload_finished(stc.test_id, background=False)
|
||||
|
||||
self.assertEqual(self.keys(run), ['stc', 'ltc'])
|
||||
self.assertEqual(len(self.creator.calls), 2)
|
||||
|
||||
def test_loops_are_capped(self):
|
||||
|
||||
again = graph(max_visits=3); again['edges'] = [{ 'from' : 'stc', 'on' : 'failed', 'to' : 'stc' }]
|
||||
run = self.start(graph=again)
|
||||
|
||||
for _ in range(5):
|
||||
running = StepRun.objects.filter(run=run, status='RUNNING').first()
|
||||
if running is None: break
|
||||
self.finish(running, failed=True)
|
||||
|
||||
self.assertEqual(self.keys(run), ['stc', 'stc', 'stc'])
|
||||
self.assertEqual(self.status(run), 'COMPLETED')
|
||||
self.assertIn('limit of 3 runs', ' '.join(PipelineRun.objects.get(id=run.id).notes))
|
||||
|
||||
def test_total_workloads_are_capped(self):
|
||||
|
||||
small = graph(max_steps=1)
|
||||
run = self.start(graph=small)
|
||||
self.finish(self.steps(run)['stc'], passed=True)
|
||||
|
||||
self.assertEqual(self.keys(run), ['stc'])
|
||||
self.assertIn('limit of 1 workloads', ' '.join(PipelineRun.objects.get(id=run.id).notes))
|
||||
|
||||
def test_a_workload_that_cannot_be_created_is_an_error(self):
|
||||
|
||||
self.creator.errors = ['dev could not be found']
|
||||
run, _ = pipelines.start_pipeline(self.pipeline())
|
||||
|
||||
stc = self.steps(run)['stc']
|
||||
self.assertEqual((stc.status, run.status), ('ERROR', 'ERROR'))
|
||||
self.assertIn('could not be found', stc.message)
|
||||
|
||||
def test_an_exception_while_creating_is_contained(self):
|
||||
|
||||
self.creator.explode = True
|
||||
run, _ = pipelines.start_pipeline(self.pipeline())
|
||||
self.assertEqual(self.steps(run)['stc'].status, 'ERROR')
|
||||
|
||||
def test_an_error_on_one_branch_lets_the_other_finish(self):
|
||||
|
||||
both = graph(); both['edges'].append({ 'from' : 'stc', 'on' : 'passed', 'to' : 'retry' })
|
||||
run = self.start(graph=both)
|
||||
|
||||
self.creator.errors = ['nope'] # Every following creation fails
|
||||
self.finish(self.steps(run)['stc'], passed=True)
|
||||
|
||||
self.assertEqual(self.status(run), 'ERROR')
|
||||
self.assertEqual([s.status for s in StepRun.objects.filter(run=run).order_by('id')], ['PASSED', 'ERROR', 'ERROR'])
|
||||
|
||||
def test_disabling_the_pipeline_stops_it_from_carrying_on(self):
|
||||
|
||||
run = self.start()
|
||||
Pipeline.objects.filter(id=run.pipeline_id).update(enabled=False)
|
||||
self.finish(self.steps(run)['stc'], passed=True)
|
||||
|
||||
self.assertEqual(self.keys(run), ['stc'])
|
||||
self.assertEqual(self.status(run), 'CANCELLED')
|
||||
|
||||
def test_an_author_who_is_no_longer_enabled_cannot_create(self):
|
||||
|
||||
self.profile.enabled = False; self.profile.save()
|
||||
run, _ = pipelines.start_pipeline(self.pipeline())
|
||||
|
||||
self.assertEqual(self.steps(run)['stc'].status, 'ERROR')
|
||||
self.assertIn('not an enabled user', self.steps(run)['stc'].message)
|
||||
self.assertEqual(self.creator.calls, [])
|
||||
|
||||
def test_unrelated_workloads_are_ignored(self):
|
||||
|
||||
other = Test.objects.create(
|
||||
author='alice', book_name='b', dev=self.engine, dev_repo='r', dev_engine='e', dev_options='o',
|
||||
dev_time_control='1+1', base=self.engine, base_repo='r', base_engine='e', base_options='o',
|
||||
base_time_control='1+1', finished=True)
|
||||
|
||||
with self.assertNumQueries(1):
|
||||
pipelines.workload_finished(other.id, background=False)
|
||||
|
||||
class CatchUpTests(PipelineTestCase):
|
||||
|
||||
def test_resolves_a_workload_that_ended_unnoticed(self):
|
||||
|
||||
run = self.start()
|
||||
Test.objects.filter(id=self.steps(run)['stc'].test_id).update(finished=True, passed=True) # No hook
|
||||
|
||||
self.assertEqual(self.keys(run), ['stc'])
|
||||
found = pipelines.catch_up()
|
||||
|
||||
self.assertEqual(found['resolved'], 1)
|
||||
self.assertEqual(self.keys(run), ['stc', 'ltc'])
|
||||
|
||||
def test_relaunches_an_abandoned_launch(self):
|
||||
|
||||
run = self.start()
|
||||
stc = self.steps(run)['stc']
|
||||
|
||||
# Pretend the process died while launching, long ago
|
||||
old = timezone.now() - timedelta(seconds=pipelines.STALE_LAUNCH_SECONDS + 60)
|
||||
StepRun.objects.filter(id=stc.id).update(status='LAUNCHING', test_id=0, updated=old)
|
||||
calls = len(self.creator.calls)
|
||||
|
||||
found = pipelines.catch_up()
|
||||
|
||||
self.assertEqual(found['relaunched'], 1)
|
||||
self.assertEqual(len(self.creator.calls), calls + 1)
|
||||
self.assertEqual(self.steps(run)['stc'].status, 'RUNNING')
|
||||
|
||||
def test_leaves_a_recent_launch_alone(self):
|
||||
|
||||
run = self.start()
|
||||
stc = self.steps(run)['stc']
|
||||
StepRun.objects.filter(id=stc.id).update(status='LAUNCHING', test_id=0)
|
||||
|
||||
self.assertEqual(pipelines.catch_up()['relaunched'], 0)
|
||||
|
||||
def test_does_nothing_when_all_is_well(self):
|
||||
|
||||
self.start()
|
||||
self.assertEqual(pipelines.catch_up(), { 'relaunched' : 0, 'resolved' : 0 })
|
||||
|
||||
class AuditTests(PipelineTestCase):
|
||||
|
||||
def test_events_are_logged(self):
|
||||
|
||||
run = self.start()
|
||||
self.finish(self.steps(run)['stc'], passed=True)
|
||||
|
||||
summaries = list(LogEvent.objects.values_list('summary', flat=True))
|
||||
self.assertTrue(any('STARTED' in s for s in summaries))
|
||||
self.assertTrue(any(s.endswith('stc PASSED') for s in summaries))
|
||||
|
||||
class CancelTests(PipelineTestCase):
|
||||
|
||||
def test_cancelling_stops_whatever_has_not_started_and_lets_the_rest_run(self):
|
||||
|
||||
both = graph(); both['edges'].append({ 'from' : 'stc', 'on' : 'passed', 'to' : 'retry' })
|
||||
run = self.start(graph=both)
|
||||
stc = self.steps(run)['stc']
|
||||
|
||||
queued = StepRun.objects.create(run=run, step_key='ltc', kind='TEST', payload=payload()) # Waiting
|
||||
self.assertTrue(pipelines.cancel_run(run.id, 'alice'))
|
||||
|
||||
self.assertEqual(self.status(run), 'CANCELLED')
|
||||
self.assertEqual(StepRun.objects.get(id=queued.id).status, 'STOPPED')
|
||||
self.assertEqual(StepRun.objects.get(id=stc.id).status, 'RUNNING') # Its test keeps going
|
||||
self.assertIn('alice', ' '.join(PipelineRun.objects.get(id=run.id).notes))
|
||||
|
||||
def test_a_cancelled_run_starts_nothing_and_stays_cancelled(self):
|
||||
|
||||
run = self.start()
|
||||
pipelines.cancel_run(run.id, 'alice')
|
||||
self.finish(self.steps(run)['stc'], passed=True) # Would normally start the LTC
|
||||
|
||||
self.assertEqual(self.keys(run), ['stc'])
|
||||
self.assertEqual(self.steps(run)['stc'].status, 'PASSED') # Still told how it ended
|
||||
self.assertEqual(self.status(run), 'CANCELLED')
|
||||
|
||||
def test_only_a_running_run_can_be_cancelled(self):
|
||||
|
||||
run = self.start()
|
||||
self.finish(self.steps(run)['stc'])
|
||||
self.assertEqual(self.status(run), 'COMPLETED')
|
||||
|
||||
self.assertFalse(pipelines.cancel_run(run.id, 'alice'))
|
||||
self.assertEqual(self.status(run), 'COMPLETED')
|
||||
self.assertFalse(pipelines.cancel_run(999999, 'alice'))
|
||||
|
||||
def test_cancelling_twice_is_harmless(self):
|
||||
|
||||
run = self.start()
|
||||
self.assertTrue(pipelines.cancel_run(run.id, 'alice'))
|
||||
self.assertFalse(pipelines.cancel_run(run.id, 'alice'))
|
||||
self.assertEqual(len(PipelineRun.objects.get(id=run.id).notes), 1)
|
||||
|
||||
def test_cancelling_while_a_workload_is_being_created_does_not_resurrect_the_step(self):
|
||||
|
||||
run = self.pipeline()
|
||||
started = {}
|
||||
|
||||
def click_cancel():
|
||||
started['run'] = PipelineRun.objects.get(pipeline=run)
|
||||
self.assertTrue(pipelines.cancel_run(started['run'].id, 'alice'))
|
||||
|
||||
self.creator.during = click_cancel
|
||||
made, _ = pipelines.start_pipeline(run)
|
||||
|
||||
stc = StepRun.objects.get(run=started['run'])
|
||||
self.assertEqual(stc.status, 'STOPPED') # Not flipped back to RUNNING
|
||||
self.assertNotEqual(stc.test_id, 0) # But the workload that got made is recorded
|
||||
self.assertEqual(self.status(started['run']), 'CANCELLED')
|
||||
self.assertIn('cancelled', stc.message)
|
||||
+16
-2
@@ -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),
|
||||
@@ -83,7 +98,6 @@ urlpatterns = [
|
||||
django.urls.path(r'clientWorkerInfo/', OpenBench.views.client_worker_info),
|
||||
django.urls.path(r'clientGetWorkload/', OpenBench.views.client_get_workload),
|
||||
django.urls.path(r'clientGetNetwork/<str:engine>/<str:name>/', OpenBench.views.client_get_network),
|
||||
django.urls.path(r'giteaSource/', OpenBench.views.gitea_source),
|
||||
django.urls.path(r'clientBenchError/', OpenBench.views.client_bench_error),
|
||||
django.urls.path(r'clientSubmitNPS/', OpenBench.views.client_submit_nps),
|
||||
django.urls.path(r'clientSubmitError/', OpenBench.views.client_submit_error),
|
||||
|
||||
+18
-4
@@ -436,12 +436,16 @@ def branch_is_out_of_date(test):
|
||||
if test.dev_engine != test.base_engine:
|
||||
return False
|
||||
|
||||
import OpenBench.git_hosts
|
||||
# Format the request to the Github endpoint
|
||||
base = 'https://api.github.com/repos/'
|
||||
base = test.dev_repo.replace('github.com', 'api.github.com/repos')
|
||||
url = path_join(base, 'compare', '%s...%s' % (test.dev.sha, test.base.sha))
|
||||
|
||||
try:
|
||||
# Out of date if the base has commits that the dev branch lacks
|
||||
headers = OpenBench.git_hosts.api_headers(test.dev_engine, test.dev_repo)
|
||||
return OpenBench.git_hosts.commits_ahead(test.dev_repo, test.dev.sha, test.base.sha, headers) > 0
|
||||
# Out of date if ahead_by is non-zero
|
||||
headers = read_git_credentials(test.dev_engine)
|
||||
data = requests.get(url, headers=headers).json()
|
||||
return data.get('ahead_by', 0) > 0
|
||||
|
||||
except:
|
||||
# If something went wrong, just ignore it
|
||||
@@ -603,6 +607,12 @@ def network_edit(request, engine, network):
|
||||
return OpenBench.views.redirect(request, '/networks/%s' % (network.engine), status='Applied changes')
|
||||
|
||||
|
||||
def notify_pipelines(test_id):
|
||||
|
||||
# Imported late, since Pipelines create Workloads, which depend on this module
|
||||
import OpenBench.pipelines
|
||||
OpenBench.pipelines.workload_finished(test_id)
|
||||
|
||||
def update_test(request, machine):
|
||||
|
||||
# Extract error information
|
||||
@@ -695,6 +705,10 @@ def update_test(request, machine):
|
||||
if should_record_llr:
|
||||
record_llr_history(test)
|
||||
|
||||
# Tell any Pipeline that cares, once the Workload is truly saved
|
||||
if test.finished:
|
||||
transaction.on_commit(lambda: notify_pipelines(test_id))
|
||||
|
||||
# Update Result object; No risk from concurrent access
|
||||
Result.objects.filter(id=result_id).update(
|
||||
games = F('games' ) + games,
|
||||
|
||||
+4
-29
@@ -25,7 +25,6 @@ import django.shortcuts
|
||||
import django.contrib.auth
|
||||
|
||||
import OpenBench.config
|
||||
import OpenBench.git_hosts
|
||||
import OpenBench.utils
|
||||
import OpenBench.uiutils
|
||||
|
||||
@@ -233,10 +232,7 @@ def profile_config(request):
|
||||
|
||||
for (engine, current_repo) in profile.repos.items():
|
||||
repo_name = request.POST.get('engine-repo-%s' % (engine), '').removesuffix('/')
|
||||
repo = repo_name if repo_name.startswith('https://') else 'https://github.com/%s' % (repo_name)
|
||||
|
||||
if repo_name and not OpenBench.git_hosts.is_valid_repo(repo):
|
||||
return redirect(request, '/profile/', error='Repositories must be on Github or a configured Gitea server')
|
||||
repo = 'https://github.com/%s' % (repo_name)
|
||||
|
||||
if repo != current_repo and repo_name:
|
||||
changes += 'Updated Engine: %s to use %s\n' % (engine, repo)
|
||||
@@ -250,8 +246,8 @@ def profile_config(request):
|
||||
|
||||
if engine_name != 'None' and engine_repo:
|
||||
|
||||
if not OpenBench.git_hosts.is_valid_repo(engine_repo):
|
||||
return redirect(request, '/profile/', error='Repositories must be on Github or a configured Gitea server')
|
||||
if not engine_repo.startswith('https://github.com/'):
|
||||
return redirect(request, '/profile/', error='Repositories must be on Github')
|
||||
|
||||
if not profile.engine:
|
||||
profile.engine = engine_name
|
||||
@@ -806,28 +802,6 @@ def client_worker_info(request):
|
||||
# Pass back the Machine Id, and Secret Token for this session
|
||||
return JsonResponse({ 'machine_id' : machine.id, 'secret' : machine.secret })
|
||||
|
||||
def gitea_source(request):
|
||||
|
||||
# Workers download sources with a plain GET. The link carries a signature
|
||||
# made at test creation, so only repo/sha pairs this server handed out work.
|
||||
repo = request.GET.get('repo', '')
|
||||
sha = request.GET.get('sha' , '')
|
||||
sig = request.GET.get('sig' , '')
|
||||
|
||||
if not OpenBench.git_hosts.verify_source_request(repo, sha, sig):
|
||||
return django.http.HttpResponseForbidden('Invalid source link')
|
||||
|
||||
try:
|
||||
upstream = OpenBench.git_hosts.open_gitea_archive(repo, sha)
|
||||
except Exception:
|
||||
import traceback; traceback.print_exc()
|
||||
return HttpResponse('Unable to fetch the source archive', status=502)
|
||||
|
||||
owner, name = OpenBench.git_hosts.owner_and_name(repo)
|
||||
response = django.http.StreamingHttpResponse(upstream.iter_content(chunk_size=1 << 16), content_type='application/zip')
|
||||
response['Content-Disposition'] = 'attachment; filename="%s-%s.zip"' % (name, sha[:8])
|
||||
return response
|
||||
|
||||
@csrf_exempt
|
||||
def client_get_network(request, engine, name):
|
||||
|
||||
@@ -850,6 +824,7 @@ def client_bench_error(request, machine):
|
||||
# Find and stop the test with the bad bench
|
||||
test = Test.objects.get(id=int(request.POST['test_id']))
|
||||
test.finished = True; test.save()
|
||||
OpenBench.utils.notify_pipelines(test.id)
|
||||
|
||||
# Log the error into the Events table
|
||||
LogEvent.objects.create(
|
||||
|
||||
@@ -25,6 +25,7 @@
|
||||
# requested. This will return the user to the index, or a login page, with some
|
||||
# indication as to success, or a reason for failure.
|
||||
|
||||
import OpenBench.utils
|
||||
import OpenBench.views
|
||||
|
||||
from OpenBench.models import *
|
||||
@@ -59,6 +60,10 @@ def modify_workload(request, id, action=None):
|
||||
LogEvent.objects.create(author=request.user.username, summary=action, log_file='', test_id=id)
|
||||
workload.save()
|
||||
|
||||
# A Pipeline waiting on this Workload needs to know that it is over
|
||||
if action in ['STOP', 'DELETE']:
|
||||
OpenBench.utils.notify_pipelines(workload.id)
|
||||
|
||||
# Send back to the index, notifying them of the success
|
||||
return OpenBench.views.redirect(request, '/index/', status=message)
|
||||
|
||||
|
||||
@@ -42,7 +42,6 @@ import requests
|
||||
import traceback
|
||||
|
||||
import OpenBench.config
|
||||
import OpenBench.git_hosts
|
||||
import OpenBench.utils
|
||||
|
||||
from OpenBench.models import *
|
||||
@@ -246,10 +245,9 @@ def verify_draw_adj(errors, request, field):
|
||||
except: errors.append('Invalid Draw Adjudication Setting. Try "None"?')
|
||||
|
||||
def verify_github_repo(errors, request, field):
|
||||
try: assert OpenBench.git_hosts.is_valid_repo(request.POST[field])
|
||||
except:
|
||||
hosts = ', '.join('%s<User>/<Repo>' % (prefix) for prefix in OpenBench.git_hosts.repo_prefixes())
|
||||
errors.append('Sources must be found on %s' % (hosts))
|
||||
pattern = r'^https:\/\/github\.com\/[A-Za-z0-9-]+\/[A-Za-z0-9_.-]+\/?$'
|
||||
try: assert re.match(pattern, request.POST[field])
|
||||
except: errors.append('Sources must be found on https://github.com/<User>/<Repo>')
|
||||
|
||||
def verify_network(errors, request, field, field_name, engine_field):
|
||||
try:
|
||||
@@ -355,26 +353,19 @@ def collect_github_info(errors, request, field):
|
||||
|
||||
# Get branch name / commit sha / tag, and the API path for it
|
||||
branch = request.POST['{0}_branch'.format(field)]
|
||||
bysha = bool(re.search('^[0-9a-fA-F]{40}$', branch))
|
||||
|
||||
# All API requests will share this common path. Some engines are private.
|
||||
repo = request.POST['%s_repo' % (field)]
|
||||
base = OpenBench.git_hosts.api_base(repo)
|
||||
base = request.POST['%s_repo' % (field)].replace('github.com', 'api.github.com/repos')
|
||||
engine = request.POST['%s_engine' % (field)]
|
||||
private = OpenBench.config.OPENBENCH_CONFIG['engines'][engine]['private']
|
||||
gitea = OpenBench.git_hosts.is_gitea(repo)
|
||||
headers = {}
|
||||
|
||||
## Step 1: Verify the target of the API requests
|
||||
## [A] We will not attempt to reach any site other than api.github.com,
|
||||
## or a Gitea server listed under "gitea_hosts" in the config
|
||||
## [A] We will not attempt to reach any site other than api.github.com
|
||||
## [B] Private engines may only use their main repo for sources of tests
|
||||
## [C] Determine which, if any, credentials we want to pass along
|
||||
|
||||
# Private engines rely on Github Actions artifacts, which Gitea does not offer
|
||||
if private and gitea:
|
||||
errors.append('Private engines must be hosted on Github')
|
||||
return (None, None)
|
||||
|
||||
# Private engines must have a token stored in credentials.enginename
|
||||
if private and not (headers := OpenBench.utils.read_git_credentials(engine)):
|
||||
errors.append('Server does not have access tokens for this engine')
|
||||
@@ -386,51 +377,59 @@ def collect_github_info(errors, request, field):
|
||||
return (None, None)
|
||||
|
||||
# Avoid leaking our credentials to other websites
|
||||
if not OpenBench.git_hosts.is_valid_repo(repo):
|
||||
errors.append('OpenBench may only reach Github\'s API or a configured Gitea server')
|
||||
if not base.startswith('https://api.github.com/'):
|
||||
errors.append('OpenBench may only reach Github\'s API')
|
||||
return (None, None)
|
||||
|
||||
# Gitea servers get their own token if there is one, and nothing else.
|
||||
# Without a token the repository has to be readable anonymously.
|
||||
if gitea:
|
||||
headers = OpenBench.git_hosts.gitea_headers()
|
||||
|
||||
## Step 2: Connect to the Github or Gitea API for the given Branch or Commit SHA.
|
||||
## Step 2: Connect to the Github API for the given Branch or Commit SHA.
|
||||
## [A] We will attempt to parse the most recent commit message for a
|
||||
## bench, unless one was supplied.
|
||||
## [B] We will translate any branch name into a commit SHA for later use,
|
||||
## so we may compare branches and generate diff URLs
|
||||
## [C] If the engine is public, we will construct the URL to download the
|
||||
## source code into a .zip file. Gitea sources go through this server.
|
||||
## source code from Github into a .zip file.
|
||||
## [D] If the engine is private, we will carry onto Step 3.
|
||||
|
||||
try: # Resolve the branch, tag, or commit sha
|
||||
commit = OpenBench.git_hosts.fetch_commit(repo, branch, headers)
|
||||
assert commit['message'] is not None and commit['sha']
|
||||
assert private or commit['tree']
|
||||
try: # Fetch data from the Github API
|
||||
|
||||
# Lookup branch or commit sha, but will fail for tags
|
||||
url = OpenBench.utils.path_join(base, 'commits' if bysha else 'branches', branch)
|
||||
data = requests.get(url, headers=headers).json()
|
||||
|
||||
# Check to see if the branch name was actually a tag name
|
||||
if not bysha and 'commit' not in data:
|
||||
url = OpenBench.utils.path_join(base, 'commits', branch)
|
||||
data = requests.get(url, headers=headers).json()
|
||||
|
||||
# Actual branches have to go one layer deeper
|
||||
elif not bysha: data = data['commit']
|
||||
|
||||
# Check that all the data we need going forward is present
|
||||
assert 'message' in data['commit'] and 'sha' in data
|
||||
assert private or 'sha' in data['commit']['tree']
|
||||
|
||||
except: # Unable to find for whatever reason
|
||||
traceback.print_exc()
|
||||
hint = ' (no Gitea token on the server, so the repository must be public)' if gitea and not headers else ''
|
||||
errors.append('%s could not be found%s' % (branch or 'Branch', hint))
|
||||
errors.append('%s could not be found' % (branch or 'Branch'))
|
||||
return (None, None)
|
||||
|
||||
# Extract the bench from the web form, or from the commit message
|
||||
if not (bench := determine_bench(request, field, commit['message'])):
|
||||
if not (bench := determine_bench(request, field, data['commit']['message'])):
|
||||
errors.append('Unable to parse a Bench for %s' % (branch))
|
||||
return (None, None)
|
||||
|
||||
# Public Engines: Construct the .zip download and return everything
|
||||
if not private:
|
||||
source = OpenBench.git_hosts.source_url(request, repo, commit)
|
||||
return (source, branch, commit['sha'], bench), True
|
||||
treeurl = data['commit']['tree']['sha'] + '.zip'
|
||||
source = OpenBench.utils.path_join(request.POST['%s_repo' % (field)], 'archive', treeurl)
|
||||
return (source, branch, data['sha'], bench), True
|
||||
|
||||
## Step 3: Construct the URL for the API request to list all Artifacts
|
||||
## [A] OpenBench artifacts are always run via a file named openbench.yml
|
||||
## [B] These should contain combinations for windows/linux, avx2/avx512, popcnt/pext
|
||||
## [C] If those artifacts are not found, we flag the test as awaiting, and try later.
|
||||
|
||||
url, has_all = fetch_artifact_url(base, engine, headers, commit['sha'])
|
||||
url, has_all = fetch_artifact_url(base, engine, headers, data['sha'])
|
||||
return (url, branch, data['sha'], bench), has_all
|
||||
|
||||
def requests_illegal_fork(request, field):
|
||||
|
||||
@@ -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>
|
||||
|
||||
|
||||
@@ -15,8 +15,8 @@
|
||||
document.addEventListener(
|
||||
'DOMContentLoaded', function () {
|
||||
change_engine('{{ profile.engine }}', 'dev', '{{workload}}');
|
||||
enforce_default_text('dev_repo', ['https://github.com/'{% for host in config.gitea_hosts %}, '{{host}}/'{% endfor %}]);
|
||||
enforce_default_text('base_repo', ['https://github.com/'{% for host in config.gitea_hosts %}, '{{host}}/'{% endfor %}]);
|
||||
enforce_default_text('dev_repo', 'https://github.com/');
|
||||
enforce_default_text('base_repo', 'https://github.com/');
|
||||
}, false
|
||||
);
|
||||
</script>
|
||||
|
||||
@@ -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 %}
|
||||
@@ -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 %}
|
||||
@@ -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) + '&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 %}
|
||||
@@ -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 %}
|
||||
@@ -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 %}
|
||||
@@ -7,7 +7,7 @@
|
||||
<script src="{% static 'default_text.js' %}?{{ static_version }}"></script>
|
||||
|
||||
<script>
|
||||
enforce_default_text('new-engine-repo', ['https://github.com/'{% for host in config.gitea_hosts %}, '{{host}}/'{% endfor %}]);
|
||||
enforce_default_text('new-engine-repo', 'https://github.com/');
|
||||
</script>
|
||||
{% endblock %}
|
||||
|
||||
|
||||
@@ -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 %}
|
||||
|
||||
|
||||
@@ -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()
|
||||
@@ -0,0 +1,349 @@
|
||||
#!/usr/bin/python3
|
||||
|
||||
import copy
|
||||
import os
|
||||
import sys
|
||||
import unittest
|
||||
|
||||
# Needed to include from ../OpenBench/pipeline_graph.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_graph import *
|
||||
|
||||
def test_payload(**changes):
|
||||
|
||||
payload = {
|
||||
'dev_engine' : 'Stockfish', 'dev_repo' : 'https://github.com/o/r', 'dev_branch' : 'dev',
|
||||
'dev_network' : '', 'dev_options' : 'Threads=1 Hash=8', 'dev_time_control' : '8.0+0.08',
|
||||
'base_engine' : 'Stockfish', 'base_repo' : 'https://github.com/o/r', 'base_branch' : 'master',
|
||||
'base_network' : '', 'base_options' : 'Threads=1 Hash=8', 'base_time_control' : '8.0+0.08',
|
||||
'book_name' : 'UHO.epd', 'upload_pgns' : 'FALSE', 'priority' : '0', 'throughput' : '1000',
|
||||
'syzygy_wdl' : 'OPTIONAL', 'syzygy_adj' : 'OPTIONAL',
|
||||
'win_adj' : 'movecount=3 score=400', 'draw_adj' : 'movenumber=40 movecount=8 score=10',
|
||||
'workload_size' : '32', 'test_mode' : 'SPRT',
|
||||
'test_bounds' : '[0.00, 2.00]', 'test_confidence' : '[0.10, 0.10]',
|
||||
}
|
||||
|
||||
payload.update(changes)
|
||||
return payload
|
||||
|
||||
def test_step(name, **changes):
|
||||
return { 'name' : name, 'kind' : 'TEST', 'payload' : test_payload(**changes) }
|
||||
|
||||
def tune_step():
|
||||
payload = { key : value for key, value in test_payload().items() if not key.startswith('base_') }
|
||||
for key in ('workload_size', 'test_mode', 'test_bounds', 'test_confidence'): del payload[key]
|
||||
payload.update({
|
||||
'spsa_alpha' : '0.602', 'spsa_gamma' : '0.101', 'spsa_A_ratio' : '0.1',
|
||||
'spsa_iterations' : '1000', 'spsa_pairs_per' : '8',
|
||||
'spsa_reporting_type' : 'BULK', 'spsa_distribution_type' : 'SINGLE',
|
||||
'spsa_inputs' : 'Aspiration, int, 20, 5, 50, 4, 0.002' })
|
||||
return { 'name' : 'Tune', 'kind' : 'TUNE', 'payload' : payload }
|
||||
|
||||
def datagen_step():
|
||||
payload = test_payload()
|
||||
for key in ('test_mode', 'test_bounds', 'test_confidence'): del payload[key]
|
||||
payload.update({ 'datagen_max_games' : '1000', 'datagen_custom_genfens' : '', 'datagen_play_reverses' : 'NO' })
|
||||
return { 'name' : 'Data', 'kind' : 'DATAGEN', 'payload' : payload }
|
||||
|
||||
def stc_then_ltc():
|
||||
|
||||
return {
|
||||
'version' : 1, 'start' : 'stc',
|
||||
'steps' : {
|
||||
'stc' : test_step('STC'),
|
||||
'ltc' : test_step('LTC', dev_time_control='40.0+0.40', base_time_control='40.0+0.40'),
|
||||
'retry' : test_step('STC wider', test_bounds='[-1.00, 3.00]'),
|
||||
},
|
||||
'edges' : [
|
||||
{ 'from' : 'stc', 'on' : 'passed', 'to' : 'ltc' },
|
||||
{ 'from' : 'stc', 'on' : 'failed', 'to' : 'retry' },
|
||||
],
|
||||
}
|
||||
|
||||
def codes(issues, level=None):
|
||||
return sorted(i['code'] for i in issues if level is None or i['level'] == level)
|
||||
|
||||
class ValidationTests(unittest.TestCase):
|
||||
|
||||
def test_valid_graph_has_no_errors(self):
|
||||
issues = validate_graph(stc_then_ltc())
|
||||
self.assertFalse(has_errors(issues), issues)
|
||||
|
||||
def test_stopped_branch_is_reported_as_info_only(self):
|
||||
issues = validate_graph(stc_then_ltc())
|
||||
self.assertEqual(codes(issues, 'info'), ['branch.uncovered'])
|
||||
self.assertIn('stopped', issues[0]['message'])
|
||||
|
||||
def test_garbage_input(self):
|
||||
for garbage in (None, [], 'x', 5, {}):
|
||||
self.assertTrue(has_errors(validate_graph(garbage)))
|
||||
|
||||
def test_missing_start(self):
|
||||
graph = stc_then_ltc(); graph['start'] = 'nope'
|
||||
self.assertIn('start.missing', codes(validate_graph(graph), 'error'))
|
||||
|
||||
def test_bad_edge_references(self):
|
||||
graph = stc_then_ltc()
|
||||
graph['edges'].append({ 'from' : 'ghost', 'on' : 'passed', 'to' : 'ltc' })
|
||||
graph['edges'].append({ 'from' : 'ltc', 'on' : 'passed', 'to' : 'ghost' })
|
||||
graph['edges'].append({ 'from' : 'ltc', 'on' : 'sometimes', 'to' : None })
|
||||
found = codes(validate_graph(graph), 'error')
|
||||
self.assertIn('edge.from', found); self.assertIn('edge.to', found); self.assertIn('edge.on', found)
|
||||
|
||||
def test_duplicate_edge(self):
|
||||
graph = stc_then_ltc()
|
||||
graph['edges'].append(copy.deepcopy(graph['edges'][0]))
|
||||
self.assertIn('edge.duplicate', codes(validate_graph(graph), 'error'))
|
||||
|
||||
def test_missing_and_conditional_payload_fields(self):
|
||||
graph = stc_then_ltc()
|
||||
del graph['steps']['ltc']['payload']['dev_repo']
|
||||
del graph['steps']['stc']['payload']['test_bounds']
|
||||
graph['steps']['retry']['payload']['test_mode'] = 'GAMES'
|
||||
issues = validate_graph(graph)
|
||||
messages = ' '.join(i['message'] for i in issues if i['code'] == 'payload.missing')
|
||||
self.assertIn('dev_repo', messages); self.assertIn('test_bounds', messages); self.assertIn('test_max_games', messages)
|
||||
|
||||
def test_bad_kind_mode_and_value_types(self):
|
||||
graph = stc_then_ltc()
|
||||
graph['steps']['stc']['kind'] = 'WHAT'
|
||||
graph['steps']['ltc']['payload']['test_mode'] = 'NOPE'
|
||||
graph['steps']['retry']['payload']['priority'] = True
|
||||
found = codes(validate_graph(graph), 'error')
|
||||
self.assertIn('step.kind', found); self.assertIn('payload.test_mode', found); self.assertIn('payload.type', found)
|
||||
|
||||
def test_numbers_are_allowed_in_payload(self):
|
||||
graph = stc_then_ltc()
|
||||
graph['steps']['stc']['payload']['priority'] = 5
|
||||
graph['steps']['stc']['payload']['throughput'] = 1000.0
|
||||
self.assertFalse(has_errors(validate_graph(graph)))
|
||||
|
||||
def test_bad_step_ids(self):
|
||||
graph = stc_then_ltc()
|
||||
graph['steps']['has space'] = test_step('x')
|
||||
self.assertIn('step.id', codes(validate_graph(graph), 'error'))
|
||||
|
||||
def test_edge_override_must_be_known_field(self):
|
||||
graph = stc_then_ltc()
|
||||
graph['edges'][0]['set'] = { 'rm_rf' : '1' }
|
||||
self.assertIn('edge.set.key', codes(validate_graph(graph), 'error'))
|
||||
|
||||
def test_limits(self):
|
||||
for key, value in (('max_visits', 0), ('max_visits', 11), ('max_steps', 51), ('max_steps', 'x'), ('max_steps', True)):
|
||||
graph = stc_then_ltc(); graph[key] = value
|
||||
self.assertIn('limits.%s' % (key), codes(validate_graph(graph), 'error'), (key, value))
|
||||
|
||||
def test_too_many_steps(self):
|
||||
graph = stc_then_ltc()
|
||||
for i in range(LIMIT_STEPS): graph['steps']['s%d' % (i)] = test_step('s')
|
||||
self.assertIn('steps.limit', codes(validate_graph(graph), 'error'))
|
||||
|
||||
def test_unreachable_step_is_a_warning(self):
|
||||
graph = stc_then_ltc()
|
||||
graph['steps']['island'] = test_step('Island')
|
||||
issues = validate_graph(graph)
|
||||
self.assertFalse(has_errors(issues))
|
||||
self.assertEqual([i['step'] for i in issues if i['code'] == 'step.unreachable'], ['island'])
|
||||
|
||||
def test_loop_is_a_warning_naming_the_cap(self):
|
||||
graph = stc_then_ltc()
|
||||
graph['edges'].append({ 'from' : 'retry', 'on' : 'failed', 'to' : 'stc' })
|
||||
issues = validate_graph(graph)
|
||||
self.assertFalse(has_errors(issues))
|
||||
loops = [i for i in issues if i['code'] == 'loop']
|
||||
self.assertEqual(len(loops), 1)
|
||||
self.assertIn('capped at 3', loops[0]['message'])
|
||||
|
||||
def test_self_loop_is_detected(self):
|
||||
graph = stc_then_ltc()
|
||||
graph['edges'][1]['to'] = 'stc'
|
||||
self.assertIn('loop', codes(validate_graph(graph), 'warning'))
|
||||
|
||||
def test_tune_and_datagen_steps_are_valid(self):
|
||||
graph = stc_then_ltc()
|
||||
graph['steps']['tune'] = tune_step()
|
||||
graph['steps']['data'] = datagen_step()
|
||||
graph['edges'].append({ 'from' : 'ltc', 'on' : 'passed', 'to' : 'tune' })
|
||||
graph['edges'].append({ 'from' : 'tune', 'on' : 'passed', 'to' : 'data' })
|
||||
self.assertFalse(has_errors(validate_graph(graph)), validate_graph(graph))
|
||||
|
||||
def test_missing_tune_fields(self):
|
||||
graph = stc_then_ltc()
|
||||
graph['steps']['tune'] = tune_step()
|
||||
del graph['steps']['tune']['payload']['spsa_inputs']
|
||||
graph['edges'].append({ 'from' : 'ltc', 'on' : 'passed', 'to' : 'tune' })
|
||||
self.assertIn('payload.missing', codes(validate_graph(graph), 'error'))
|
||||
|
||||
def test_impossible_outcome_for_tunes_and_datagen(self):
|
||||
graph = stc_then_ltc()
|
||||
graph['steps']['tune'] = tune_step()
|
||||
graph['steps']['data'] = datagen_step()
|
||||
graph['edges'].append({ 'from' : 'ltc', 'on' : 'passed', 'to' : 'tune' })
|
||||
graph['edges'].append({ 'from' : 'tune', 'on' : 'failed', 'to' : 'data' })
|
||||
graph['edges'].append({ 'from' : 'data', 'on' : 'failed', 'to' : None })
|
||||
|
||||
issues = validate_graph(graph)
|
||||
self.assertFalse(has_errors(issues), issues)
|
||||
self.assertEqual([i['step'] for i in issues if i['code'] == 'edge.impossible'], ['tune', 'data'])
|
||||
|
||||
def test_failed_edge_from_a_test_is_not_impossible(self):
|
||||
self.assertNotIn('edge.impossible', codes(validate_graph(stc_then_ltc())))
|
||||
|
||||
def test_any_edge_suppresses_coverage_info(self):
|
||||
graph = stc_then_ltc()
|
||||
graph['edges'] = [{ 'from' : 'stc', 'on' : 'any', 'to' : 'ltc' }]
|
||||
self.assertNotIn('branch.uncovered', codes(validate_graph(graph)))
|
||||
|
||||
class ClassifyTests(unittest.TestCase):
|
||||
|
||||
def classify(self, **kw):
|
||||
args = dict(finished=False, deleted=False, passed=False, failed=False, test_mode='SPRT', games=0, spsa=None)
|
||||
args.update(kw)
|
||||
return classify_outcome(**args)
|
||||
|
||||
def test_running_test_has_no_outcome(self):
|
||||
self.assertIsNone(self.classify())
|
||||
|
||||
def test_passed_and_failed(self):
|
||||
self.assertEqual(self.classify(finished=True, passed=True), 'passed')
|
||||
self.assertEqual(self.classify(finished=True, failed=True), 'failed')
|
||||
|
||||
def test_finished_without_verdict_means_stopped(self):
|
||||
self.assertEqual(self.classify(finished=True), 'stopped')
|
||||
|
||||
def test_deleted_while_running_means_stopped(self):
|
||||
self.assertEqual(self.classify(deleted=True), 'stopped')
|
||||
|
||||
def test_passed_then_deleted_stays_passed(self):
|
||||
self.assertEqual(self.classify(finished=True, passed=True, deleted=True), 'passed')
|
||||
|
||||
def test_completed_tune_counts_as_passed(self):
|
||||
spsa = { 'pairs_per' : 4, 'iterations' : 10 }
|
||||
self.assertEqual(self.classify(finished=True, test_mode='SPSA', games=80, spsa=spsa), 'passed')
|
||||
self.assertEqual(self.classify(finished=True, test_mode='SPSA', games=200, spsa=spsa), 'passed')
|
||||
|
||||
def test_stopped_tune_is_stopped(self):
|
||||
spsa = { 'pairs_per' : 4, 'iterations' : 10 }
|
||||
self.assertEqual(self.classify(finished=True, test_mode='SPSA', games=79, spsa=spsa), 'stopped')
|
||||
|
||||
def test_tune_without_targets_is_never_passed(self):
|
||||
self.assertEqual(self.classify(finished=True, test_mode='SPSA', games=100, spsa={}), 'stopped')
|
||||
|
||||
class PlanTests(unittest.TestCase):
|
||||
|
||||
def test_initial_fire(self):
|
||||
fire = initial_fire(stc_then_ltc())
|
||||
self.assertEqual((fire.step_key, fire.kind, fire.via), ('stc', 'TEST', ''))
|
||||
self.assertTrue(all(isinstance(v, str) for v in fire.payload.values()))
|
||||
|
||||
def test_passed_goes_to_ltc(self):
|
||||
plan = plan_next(stc_then_ltc(), 'stc', 'passed', { 'stc' : 1 }, 1)
|
||||
self.assertEqual([f.step_key for f in plan.fires], ['ltc'])
|
||||
self.assertEqual(plan.fires[0].payload['dev_time_control'], '40.0+0.40')
|
||||
self.assertEqual(plan.fires[0].via, 'passed')
|
||||
|
||||
def test_failed_goes_to_retry(self):
|
||||
plan = plan_next(stc_then_ltc(), 'stc', 'failed', { 'stc' : 1 }, 1)
|
||||
self.assertEqual([f.step_key for f in plan.fires], ['retry'])
|
||||
|
||||
def test_unhandled_outcome_ends_the_run_with_a_note(self):
|
||||
plan = plan_next(stc_then_ltc(), 'stc', 'stopped', { 'stc' : 1 }, 1)
|
||||
self.assertEqual(plan.fires, [])
|
||||
self.assertIn('no edge', plan.notes[0])
|
||||
|
||||
def test_terminal_step_ends_the_run(self):
|
||||
plan = plan_next(stc_then_ltc(), 'ltc', 'passed', { 'stc' : 1, 'ltc' : 1 }, 2)
|
||||
self.assertEqual(plan.fires, [])
|
||||
|
||||
def test_explicit_end_edge(self):
|
||||
graph = stc_then_ltc()
|
||||
graph['edges'].append({ 'from' : 'ltc', 'on' : 'any', 'to' : None })
|
||||
self.assertFalse(has_errors(validate_graph(graph)))
|
||||
plan = plan_next(graph, 'ltc', 'failed', { 'ltc' : 1 }, 2)
|
||||
self.assertEqual(plan.fires, []); self.assertIn('ended', plan.notes[0])
|
||||
|
||||
def test_edge_overrides_apply_and_do_not_leak(self):
|
||||
graph = stc_then_ltc()
|
||||
graph['edges'][0]['set'] = { 'priority' : 9, 'test_bounds' : '[0.00, 5.00]' }
|
||||
plan = plan_next(graph, 'stc', 'passed', {}, 1)
|
||||
self.assertEqual(plan.fires[0].payload['priority'], '9')
|
||||
self.assertEqual(plan.fires[0].payload['test_bounds'], '[0.00, 5.00]')
|
||||
self.assertEqual(graph['steps']['ltc']['payload']['priority'], '0') # Graph is untouched
|
||||
|
||||
def test_fan_out_starts_every_matching_edge(self):
|
||||
graph = stc_then_ltc()
|
||||
graph['edges'].append({ 'from' : 'stc', 'on' : 'passed', 'to' : 'retry' })
|
||||
plan = plan_next(graph, 'stc', 'passed', { 'stc' : 1 }, 1)
|
||||
self.assertEqual(sorted(f.step_key for f in plan.fires), ['ltc', 'retry'])
|
||||
|
||||
def test_any_and_specific_edge_to_same_target_fire_once(self):
|
||||
graph = stc_then_ltc()
|
||||
graph['edges'].append({ 'from' : 'stc', 'on' : 'any', 'to' : 'ltc' })
|
||||
plan = plan_next(graph, 'stc', 'passed', { 'stc' : 1 }, 1)
|
||||
self.assertEqual([f.step_key for f in plan.fires], ['ltc'])
|
||||
self.assertEqual(len(plan.notes), 1)
|
||||
|
||||
def test_loop_is_capped_by_max_visits(self):
|
||||
graph = stc_then_ltc()
|
||||
graph['edges'][1]['to'] = 'stc'
|
||||
graph['max_visits'] = 3
|
||||
|
||||
plan = plan_next(graph, 'stc', 'failed', { 'stc' : 1 }, 1); self.assertEqual(len(plan.fires), 1)
|
||||
plan = plan_next(graph, 'stc', 'failed', { 'stc' : 2 }, 2); self.assertEqual(len(plan.fires), 1)
|
||||
plan = plan_next(graph, 'stc', 'failed', { 'stc' : 3 }, 3)
|
||||
self.assertEqual(plan.fires, []); self.assertIn('limit of 3 runs', plan.notes[0])
|
||||
|
||||
def test_total_workloads_are_capped_by_max_steps(self):
|
||||
graph = stc_then_ltc(); graph['max_steps'] = 2
|
||||
plan = plan_next(graph, 'stc', 'passed', { 'stc' : 1 }, 2)
|
||||
self.assertEqual(plan.fires, []); self.assertIn('limit of 2 workloads', plan.notes[0])
|
||||
|
||||
def test_max_steps_counts_fires_of_the_same_plan(self):
|
||||
graph = stc_then_ltc(); graph['max_steps'] = 2
|
||||
graph['edges'].append({ 'from' : 'stc', 'on' : 'passed', 'to' : 'retry' })
|
||||
plan = plan_next(graph, 'stc', 'passed', { 'stc' : 1 }, 1)
|
||||
self.assertEqual(len(plan.fires), 1)
|
||||
|
||||
def test_fires_are_independent_copies(self):
|
||||
graph = stc_then_ltc()
|
||||
plan = plan_next(graph, 'stc', 'passed', {}, 1)
|
||||
plan.fires[0].payload['priority'] = '99'
|
||||
self.assertEqual(graph['steps']['ltc']['payload']['priority'], '0')
|
||||
|
||||
class FollowedEdgesTests(unittest.TestCase):
|
||||
|
||||
def test_only_the_edges_that_were_gone_along(self):
|
||||
graph = stc_then_ltc()
|
||||
self.assertEqual(followed_edges(graph, [('stc', 'ltc', 'passed')]), { 0 })
|
||||
self.assertEqual(followed_edges(graph, [('stc', 'retry', 'failed')]), { 1 })
|
||||
|
||||
def test_nothing_followed_yet(self):
|
||||
self.assertEqual(followed_edges(stc_then_ltc(), []), set())
|
||||
|
||||
def test_the_outcome_has_to_match_the_edge(self):
|
||||
# stc -> ltc is only for a pass, so a fail that reached ltc some other way is not it
|
||||
self.assertEqual(followed_edges(stc_then_ltc(), [('stc', 'ltc', 'failed')]), set())
|
||||
|
||||
def test_an_any_edge_matches_every_outcome(self):
|
||||
graph = stc_then_ltc(); graph['edges'] = [{ 'from' : 'stc', 'on' : 'any', 'to' : 'ltc' }]
|
||||
for outcome in OUTCOMES:
|
||||
self.assertEqual(followed_edges(graph, [('stc', 'ltc', outcome)]), { 0 })
|
||||
|
||||
def test_a_loop_is_one_edge_however_often_it_is_gone_along(self):
|
||||
graph = stc_then_ltc(); graph['edges'][1]['to'] = 'stc'
|
||||
self.assertEqual(followed_edges(graph, [('stc', 'stc', 'failed')] * 3), { 1 })
|
||||
|
||||
class RunStatusTests(unittest.TestCase):
|
||||
|
||||
def test_status(self):
|
||||
self.assertEqual(run_status([]), 'COMPLETED')
|
||||
self.assertEqual(run_status(['PASSED', 'FAILED']), 'COMPLETED')
|
||||
self.assertEqual(run_status(['PASSED', 'RUNNING']), 'RUNNING')
|
||||
self.assertEqual(run_status(['QUEUED']), 'RUNNING')
|
||||
self.assertEqual(run_status(['LAUNCHING', 'ERROR']), 'RUNNING')
|
||||
self.assertEqual(run_status(['PASSED', 'ERROR']), 'ERROR')
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main()
|
||||
@@ -0,0 +1,310 @@
|
||||
#!/usr/bin/python3
|
||||
|
||||
import os
|
||||
import re
|
||||
import sys
|
||||
import unittest
|
||||
import xml.etree.ElementTree as ET
|
||||
|
||||
# Needed to include from ../OpenBench/pipeline_layout.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_layout import *
|
||||
|
||||
def step(name=None, **payload):
|
||||
base = { 'test_mode' : 'SPRT', 'test_bounds' : '[0.00, 2.00]', 'dev_time_control' : '8.0+0.08' }
|
||||
base.update(payload)
|
||||
return { 'name' : name, 'kind' : 'TEST', 'payload' : base }
|
||||
|
||||
def build(start, names, *edges):
|
||||
|
||||
""" build('a', 'abc', ('a', 'passed', 'b'), ('a', 'failed', 'c')) """
|
||||
|
||||
return {
|
||||
'version' : 1, 'start' : start,
|
||||
'steps' : { key : step(key.upper()) for key in names },
|
||||
'edges' : [{ 'from' : s, 'on' : on, 'to' : t } for s, on, t in edges],
|
||||
}
|
||||
|
||||
SHAPES = {
|
||||
'chain' : build('a', 'abc', ('a', 'passed', 'b'), ('b', 'passed', 'c')),
|
||||
'fork' : build('a', 'abc', ('a', 'passed', 'b'), ('a', 'failed', 'c')),
|
||||
'diamond' : build('a', 'abcd', ('a', 'passed', 'b'), ('a', 'failed', 'c'), ('b', 'any', 'd'), ('c', 'any', 'd')),
|
||||
'skip' : build('a', 'abc', ('a', 'passed', 'b'), ('b', 'passed', 'c'), ('a', 'failed', 'c')),
|
||||
'retry' : build('a', 'abc', ('a', 'passed', 'b'), ('a', 'failed', 'a'), ('b', 'failed', 'a')),
|
||||
'wide' : build('a', 'abcdef', ('a', 'any', 'b'), ('a', 'any', 'c'), ('a', 'any', 'd'), ('a', 'any', 'e'), ('a', 'any', 'f')),
|
||||
'orphans' : build('a', 'abc', ('a', 'passed', 'b')),
|
||||
'ended' : build('a', 'ab', ('a', 'passed', 'b'), ('a', 'failed', None), ('b', 'any', None)),
|
||||
'single' : build('a', 'a'),
|
||||
'wordy' : dict(build('a', 'abc', ('a', 'passed', 'b'), ('a', 'failed', 'c')),
|
||||
edges=[{ 'from' : 'a', 'on' : 'passed', 'to' : 'b', 'set' : { 'priority' : '1', 'test_bounds' : 'x', 'throughput' : '2' } },
|
||||
{ 'from' : 'a', 'on' : 'stopped', 'to' : 'c', 'set' : { k : '1' for k in ('dev_bench', 'base_bench', 'priority', 'throughput', 'book_name', 'upload_pgns', 'dev_options', 'base_options', 'dev_network', 'base_network') } }]),
|
||||
'two skips': build('a', 'abcd', ('a', 'passed', 'b'), ('b', 'passed', 'c'), ('c', 'passed', 'd'),
|
||||
('a', 'failed', 'c'), ('a', 'stopped', 'd')),
|
||||
'loop top' : build('a', 'abcd', ('a', 'any', 'b'), ('a', 'any', 'c'), ('a', 'any', 'd'), ('b', 'failed', 'a')),
|
||||
'tall' : build('a', 'abcdef', ('a', 'any', 'b'), ('a', 'any', 'c'), ('a', 'any', 'd'),
|
||||
('b', 'passed', 'e'), ('e', 'passed', 'f'), ('a', 'stopped', 'f'), ('d', 'failed', 'a')),
|
||||
}
|
||||
|
||||
def overlap(a, b):
|
||||
return not (a['x'] + a['w'] <= b['x'] or b['x'] + b['w'] <= a['x'] or
|
||||
a['y'] + a['h'] <= b['y'] or b['y'] + b['h'] <= a['y'])
|
||||
|
||||
class LayoutTests(unittest.TestCase):
|
||||
|
||||
def test_columns_follow_the_flow(self):
|
||||
nodes = layout(SHAPES['fork'])['nodes']
|
||||
self.assertEqual([nodes[k]['layer'] for k in 'abc'], [0, 1, 1])
|
||||
self.assertEqual(sorted((nodes['b']['row'], nodes['c']['row'])), [0, 1])
|
||||
|
||||
def test_a_step_sits_after_the_furthest_step_leading_into_it(self):
|
||||
self.assertEqual(layout(SHAPES['diamond'])['nodes']['d']['layer'], 2)
|
||||
self.assertEqual(layout(SHAPES['skip'])['nodes']['c']['layer'], 2) # Not 1, although a leads to it
|
||||
|
||||
def test_loops_do_not_push_steps_to_the_right(self):
|
||||
nodes = layout(SHAPES['retry'])['nodes']
|
||||
self.assertEqual((nodes['a']['layer'], nodes['b']['layer']), (0, 1))
|
||||
|
||||
def test_loop_edges_are_marked_and_dip_below_the_steps(self):
|
||||
|
||||
geometry = layout(SHAPES['retry'])
|
||||
loops = [e for e in geometry['edges'] if e['back']]
|
||||
|
||||
self.assertEqual(sorted(e['source'] for e in loops), ['a', 'b'])
|
||||
bottom = max(n['y'] + n['h'] for n in geometry['nodes'].values())
|
||||
for loop in loops:
|
||||
self.assertGreater(loop['ly'], bottom)
|
||||
self.assertGreater(geometry['height'], bottom + 30) # Room was made for them
|
||||
|
||||
def test_a_loop_onto_itself_is_a_loop(self):
|
||||
edge = [e for e in layout(SHAPES['retry'])['edges'] if e['source'] == e['target']]
|
||||
self.assertEqual(len(edge), 1); self.assertTrue(edge[0]['back'])
|
||||
|
||||
def test_steps_that_can_never_start_go_last_and_are_flagged(self):
|
||||
nodes = layout(SHAPES['orphans'])['nodes']
|
||||
self.assertTrue(nodes['a']['reachable'] and nodes['b']['reachable'])
|
||||
self.assertFalse(nodes['c']['reachable'])
|
||||
self.assertGreater(nodes['c']['layer'], nodes['b']['layer'])
|
||||
|
||||
def test_edges_leaving_one_step_use_different_ports(self):
|
||||
edges = layout(SHAPES['wide'])['edges']
|
||||
starts = [float(e['path'].split()[1]) for e in edges]
|
||||
self.assertEqual(len(set(starts)), len(starts))
|
||||
|
||||
def test_an_edge_to_nowhere_is_a_short_stub(self):
|
||||
ends = [e for e in layout(SHAPES['ended'])['edges'] if e['end']]
|
||||
self.assertEqual(len(ends), 2)
|
||||
self.assertTrue(all('ex' in e and e['ex'] > 0 for e in ends))
|
||||
|
||||
def test_the_stub_of_an_edge_to_nowhere_is_longer_than_its_label(self):
|
||||
for edge in [e for e in layout(SHAPES['ended'])['edges'] if e['end']]:
|
||||
self.assertGreaterEqual(edge['length'], label_width(edge_label(edge['on'], edge['changes'])) + 30)
|
||||
|
||||
def test_edges_pointing_at_missing_steps_are_skipped_not_fatal(self):
|
||||
graph = build('a', 'ab', ('a', 'passed', 'b'))
|
||||
graph['edges'].append({ 'from' : 'a', 'on' : 'failed', 'to' : 'ghost' })
|
||||
graph['edges'].append({ 'from' : 'ghost', 'on' : 'failed', 'to' : 'a' })
|
||||
self.assertEqual(len(layout(graph)['edges']), 1)
|
||||
|
||||
def test_nothing_overlaps_and_everything_fits_in_every_shape(self):
|
||||
|
||||
for name, graph in SHAPES.items():
|
||||
geometry = layout(graph)
|
||||
nodes = list(geometry['nodes'].values())
|
||||
|
||||
for i, a in enumerate(nodes):
|
||||
self.assertGreaterEqual(a['x'], 0, name); self.assertGreaterEqual(a['y'], 0, name)
|
||||
self.assertLessEqual(a['x'] + a['w'], geometry['width'], name)
|
||||
self.assertLessEqual(a['y'] + a['h'], geometry['height'], name)
|
||||
for b in nodes[i + 1:]:
|
||||
self.assertFalse(overlap(a, b), '%s: %s overlaps %s' % (name, a['id'], b['id']))
|
||||
|
||||
def test_layout_is_deterministic(self):
|
||||
for graph in SHAPES.values():
|
||||
self.assertEqual(layout(graph), layout(graph))
|
||||
|
||||
def points(path, steps=40):
|
||||
|
||||
""" Points along an edge, from its SVG path ( only M, L and C are ever used ) """
|
||||
|
||||
tokens = re.findall(r'[MLC]|-?\d+\.?\d*', path)
|
||||
found, here, i = [], None, 0
|
||||
|
||||
while i < len(tokens):
|
||||
command = tokens[i]; i += 1
|
||||
count = 6 if command == 'C' else 2
|
||||
numbers = [float(n) for n in tokens[i:i + count]]; i += count
|
||||
|
||||
if command == 'M':
|
||||
here = (numbers[0], numbers[1])
|
||||
elif command == 'L':
|
||||
for k in range(steps + 1):
|
||||
found.append((here[0] + (numbers[0] - here[0]) * k / steps, here[1] + (numbers[1] - here[1]) * k / steps))
|
||||
here = (numbers[0], numbers[1])
|
||||
else:
|
||||
(x0, y0), (x1, y1, x2, y2, x3, y3) = here, numbers
|
||||
for k in range(steps + 1):
|
||||
u = k / steps; v = 1 - u
|
||||
found.append((v**3 * x0 + 3 * v * v * u * x1 + 3 * v * u * u * x2 + u**3 * x3,
|
||||
v**3 * y0 + 3 * v * v * u * y1 + 3 * v * u * u * y2 + u**3 * y3))
|
||||
here = (x3, y3)
|
||||
|
||||
return found
|
||||
|
||||
def inside(point, node, margin=1.5):
|
||||
return (node['x'] + margin < point[0] < node['x'] + node['w'] - margin and
|
||||
node['y'] + margin < point[1] < node['y'] + node['h'] - margin)
|
||||
|
||||
class RoutingTests(unittest.TestCase):
|
||||
|
||||
def test_no_forward_edge_runs_through_a_step_that_is_not_its_own(self):
|
||||
|
||||
for name, graph in SHAPES.items():
|
||||
geometry = layout(graph)
|
||||
for edge in geometry['edges']:
|
||||
|
||||
if edge['back'] or edge['end']:
|
||||
continue # Loops run under the steps, and say so below
|
||||
|
||||
others = [n for k, n in geometry['nodes'].items() if k not in (edge['source'], edge['target'])]
|
||||
for point in points(edge['path']):
|
||||
for node in others:
|
||||
self.assertFalse(inside(point, node), '%s: edge %d cuts through %s at %s' % (name, edge['index'], node['id'], point))
|
||||
|
||||
def test_an_edge_that_skips_a_column_runs_above_the_steps_in_between(self):
|
||||
|
||||
geometry = layout(SHAPES['skip'])
|
||||
skipper = [e for e in geometry['edges'] if e['source'] == 'a' and e['target'] == 'c'][0]
|
||||
between = geometry['nodes']['b']
|
||||
|
||||
self.assertLess(skipper['ly'], between['y'])
|
||||
self.assertGreaterEqual(skipper['ly'], 0)
|
||||
|
||||
def test_every_label_fits_in_the_gap_that_it_sits_in(self):
|
||||
|
||||
for name, graph in SHAPES.items():
|
||||
geometry = layout(graph)
|
||||
|
||||
for edge in geometry['edges']:
|
||||
if edge['back'] or edge['end'] or geometry['nodes'][edge['target']]['layer'] - geometry['nodes'][edge['source']]['layer'] != 1:
|
||||
continue
|
||||
|
||||
width = label_width(edge_label(edge['on'], edge['changes']))
|
||||
right = geometry['nodes'][edge['source']]['x'] + NODE_W
|
||||
left = geometry['nodes'][edge['target']]['x']
|
||||
|
||||
self.assertGreaterEqual(edge['lx'] - width / 2, right, '%s: label sticks into the step before it' % (name))
|
||||
self.assertLessEqual(edge['lx'] + width / 2, left, '%s: label sticks into the step after it' % (name))
|
||||
|
||||
def test_every_edge_stays_on_the_canvas(self):
|
||||
|
||||
for name, graph in SHAPES.items():
|
||||
geometry = layout(graph)
|
||||
for edge in geometry['edges']:
|
||||
for x, y in points(edge['path']):
|
||||
self.assertTrue(-1 <= x <= geometry['width'] + 1 and -1 <= y <= geometry['height'] + 1, '%s: edge %d at %s' % (name, edge['index'], (x, y)))
|
||||
|
||||
def test_loops_run_under_every_step_not_just_their_own(self):
|
||||
|
||||
for name in ('retry', 'tall', 'loop top'):
|
||||
geometry = layout(SHAPES[name])
|
||||
lowest = max(n['y'] + n['h'] for n in geometry['nodes'].values())
|
||||
|
||||
for edge in [e for e in geometry['edges'] if e['back']]:
|
||||
self.assertGreater(edge['ly'], lowest, name)
|
||||
|
||||
def test_the_lines_inside_a_step_do_not_share_a_row_with_the_name(self):
|
||||
|
||||
root = ET.fromstring(render_svg(SHAPES['single'], states={ 'a' : { 'status' : 'running', 'runs' : 2 } }))
|
||||
ys = { t.get('class') : float(t.get('y')) for t in root.iter('{http://www.w3.org/2000/svg}text') if t.get('class') }
|
||||
|
||||
self.assertLess(ys['pl-name'], ys['pl-what']); self.assertLess(ys['pl-what'], ys['pl-speed'])
|
||||
self.assertEqual(ys['pl-speed'], ys['pl-status']) # Sharing the last row, on opposite sides
|
||||
|
||||
class DrawingTests(unittest.TestCase):
|
||||
|
||||
def parse(self, svg):
|
||||
return ET.fromstring(svg) # Raises if the markup is not well formed
|
||||
|
||||
def texts(self, root):
|
||||
return [''.join(t.itertext()) for t in root.iter('{http://www.w3.org/2000/svg}text')]
|
||||
|
||||
def test_every_shape_draws_well_formed_svg(self):
|
||||
for name, graph in SHAPES.items():
|
||||
root = self.parse(render_svg(graph))
|
||||
self.assertEqual(root.tag, '{http://www.w3.org/2000/svg}svg', name)
|
||||
|
||||
def test_step_names_and_conditions_are_drawn(self):
|
||||
texts = self.texts(self.parse(render_svg(SHAPES['fork'])))
|
||||
for wanted in ('A', 'B', 'C', 'passed', 'failed'):
|
||||
self.assertIn(wanted, texts)
|
||||
|
||||
def test_names_cannot_inject_markup(self):
|
||||
|
||||
graph = build('a', 'ab', ('a', 'passed', 'b'))
|
||||
graph['steps']['a']['name'] = '<script>alert(1)</script>'
|
||||
graph['steps']['b']['name'] = '"><img src=x onerror=alert(2)>'
|
||||
graph['steps']['b']['payload']['test_bounds'] = '</text><script>alert(3)</script>'
|
||||
graph['edges'][0]['set'] = { 'priority' : '"><script>alert(4)</script>' }
|
||||
|
||||
svg = render_svg(graph)
|
||||
root = self.parse(svg)
|
||||
|
||||
self.assertNotIn('<script', svg); self.assertNotIn('<img', svg)
|
||||
self.assertEqual([e.tag for e in root.iter() if 'script' in e.tag or 'img' in e.tag], [])
|
||||
self.assertTrue(any(t.startswith('<script>alert(1)') for t in self.texts(root))) # Shown as text, not run
|
||||
|
||||
def test_ids_cannot_break_out_of_attributes(self):
|
||||
graph = build('a', 'a')
|
||||
graph['steps']['x"onload="alert(1)'] = step('X')
|
||||
root = self.parse(render_svg(graph))
|
||||
for element in root.iter():
|
||||
self.assertNotIn('onload', element.attrib)
|
||||
|
||||
def test_state_decides_the_look(self):
|
||||
svg = render_svg(SHAPES['fork'], states={
|
||||
'a' : { 'status' : 'PASSED' }, 'b' : { 'status' : 'running', 'runs' : 2 }, 'c' : { 'status' : 'nonsense' } })
|
||||
root = self.parse(svg)
|
||||
classes = { g.get('data-step') : g.get('class') for g in root.iter('{http://www.w3.org/2000/svg}g') if g.get('data-step') }
|
||||
self.assertIn('pl-s-passed', classes['a']); self.assertIn('pl-s-running', classes['b'])
|
||||
self.assertIn('pl-s-idle', classes['c']) # Unknown status never becomes a class
|
||||
self.assertIn('running x2', self.texts(root))
|
||||
|
||||
def test_followed_edges_stand_out(self):
|
||||
root = self.parse(render_svg(SHAPES['fork'], taken={ 0 }))
|
||||
classes = { g.get('data-edge') : g.get('class') for g in root.iter('{http://www.w3.org/2000/svg}g') if g.get('data-edge') }
|
||||
self.assertIn('pl-taken', classes['0']); self.assertIn('pl-idle', classes['1'])
|
||||
|
||||
def test_without_a_run_no_edge_is_quiet(self):
|
||||
svg = render_svg(SHAPES['fork'])
|
||||
self.assertNotIn('pl-idle', svg); self.assertNotIn('pl-taken', svg)
|
||||
|
||||
def test_links_must_be_paths_on_this_site(self):
|
||||
|
||||
for bad in ('http://evil.example/', '//evil.example/', 'javascript:alert(1)', ''):
|
||||
self.assertNotIn('<a ', render_svg(SHAPES['single'], states={ 'a' : { 'status' : 'running', 'url' : bad } }), bad)
|
||||
|
||||
good = render_svg(SHAPES['single'], states={ 'a' : { 'status' : 'running', 'url' : '/test/12/' } })
|
||||
self.assertIn('<a href="/test/12/">', good)
|
||||
|
||||
def test_edge_changes_are_counted_and_listed(self):
|
||||
graph = build('a', 'ab', ('a', 'passed', 'b'))
|
||||
graph['edges'][0]['set'] = { 'priority' : '5', 'test_bounds' : '[0.00, 5.00]' }
|
||||
svg = render_svg(graph)
|
||||
self.assertIn('passed (2 changes)', svg); self.assertIn('priority = 5', svg)
|
||||
|
||||
def test_summaries(self):
|
||||
self.assertEqual(step_summary(step()), ('SPRT [0.00, 2.00]', '8.0+0.08'))
|
||||
self.assertEqual(step_summary(step(test_mode='GAMES', test_max_games='40000')), ('40000 games', '8.0+0.08'))
|
||||
self.assertEqual(step_summary({ 'kind' : 'TUNE', 'payload' : { 'spsa_iterations' : '500' } })[0], 'SPSA, 500 iterations')
|
||||
self.assertEqual(step_summary({ 'kind' : 'DATAGEN', 'payload' : { 'datagen_max_games' : '9' } })[0], '9 games')
|
||||
self.assertEqual(step_summary({}), ('', ''))
|
||||
|
||||
def test_long_text_is_clipped(self):
|
||||
graph = build('a', 'a'); graph['steps']['a']['name'] = 'x' * 80
|
||||
name = [t for t in self.texts(self.parse(render_svg(graph))) if t.startswith('x')][0]
|
||||
self.assertEqual(len(name), NAME_LIMIT); self.assertTrue(name.endswith('\u2026'))
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main()
|
||||
Reference in new issue
Block a user