Compare commits
41
Commits
7e8791cbe1
...
c916ed89b5
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
c916ed89b5 | ||
|
|
5146111ad5 | ||
|
|
71b4803120 | ||
|
|
2b80f804af | ||
|
|
0df26588f9 | ||
|
|
d456f2fecf | ||
|
|
429b765657 | ||
|
|
248b11473b | ||
|
|
d77f096932 | ||
|
|
07935271cb | ||
|
|
0e39c20ef3 | ||
|
|
22bb0b934d | ||
|
|
0167e19057 | ||
|
|
efc0a42f8b | ||
|
|
87886c5771 | ||
|
|
7269fd96e9 | ||
|
|
de5ec59ece | ||
|
|
9aa7678b62 | ||
|
|
4fffbf50b4 | ||
|
|
d5cea13fd6 | ||
|
|
deb68caa64 | ||
|
|
6a024f3e5a | ||
|
|
9aa9a2b447 | ||
|
|
c367dd761a | ||
|
|
05275645f5 | ||
|
|
5793204b1b | ||
|
|
26a0394ca9 | ||
|
|
d2827ee8f3 | ||
|
|
963ba2151e | ||
|
|
977ac2e4f9 | ||
|
|
0b8862cc2c | ||
|
|
cbf4e59672 | ||
|
|
0dab31718a | ||
|
|
142296006b | ||
|
|
54538edcb1 | ||
|
|
44d6bfe7e8 | ||
|
|
e67bdfaa03 | ||
|
|
e16b2e0b60 | ||
|
|
236d69cfb8 | ||
|
|
7718d593f4 | ||
|
|
dfa7687247 |
No files matched your search
@@ -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)
|
||||
@@ -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,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,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
|
||||
@@ -0,0 +1,50 @@
|
||||
import django.http
|
||||
|
||||
# Public pages worth listing for search engines. The API, the client
|
||||
# endpoints, the account pages and the creation forms are left out on purpose.
|
||||
PUBLIC_PATHS = [
|
||||
'/',
|
||||
'/index/',
|
||||
'/greens/',
|
||||
'/users/',
|
||||
'/events/',
|
||||
'/machines/',
|
||||
'/networks/',
|
||||
]
|
||||
|
||||
# Prefixes that crawlers have no business visiting
|
||||
DISALLOWED_PREFIXES = [
|
||||
'/api/',
|
||||
'/client',
|
||||
'/scripts/',
|
||||
'/login/',
|
||||
'/register/',
|
||||
'/logout/',
|
||||
'/profile',
|
||||
'/newTest/',
|
||||
'/newTune/',
|
||||
'/newDatagen/',
|
||||
'/newNetwork/',
|
||||
]
|
||||
|
||||
def robots_txt(request):
|
||||
|
||||
lines = ['User-agent: *']
|
||||
lines += ['Disallow: {}'.format(prefix) for prefix in DISALLOWED_PREFIXES]
|
||||
lines += ['', 'Sitemap: {}'.format(request.build_absolute_uri('/sitemap.xml'))]
|
||||
|
||||
return django.http.HttpResponse('\n'.join(lines) + '\n', content_type='text/plain')
|
||||
|
||||
def sitemap_xml(request):
|
||||
|
||||
entries = ''.join(
|
||||
'<url><loc>{}</loc></url>'.format(request.build_absolute_uri(path))
|
||||
for path in PUBLIC_PATHS
|
||||
)
|
||||
|
||||
body = (
|
||||
'<?xml version="1.0" encoding="UTF-8"?>\n'
|
||||
'<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">{}</urlset>\n'
|
||||
).format(entries)
|
||||
|
||||
return django.http.HttpResponse(body, content_type='application/xml')
|
||||
@@ -0,0 +1,68 @@
|
||||
/* ==========================================================================
|
||||
Live updates. Loaded after refresh.css, and uses its tokens.
|
||||
========================================================================== */
|
||||
|
||||
/* The small status pill in the corner: a pulse while updates are on */
|
||||
|
||||
.live-pill {
|
||||
position: fixed;
|
||||
right: 16px;
|
||||
bottom: 16px;
|
||||
z-index: 40;
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
padding: 6px 12px 6px 10px;
|
||||
border: 1px solid var(--line-strong);
|
||||
border-radius: 999px;
|
||||
background: rgba(26, 29, 34, 0.92);
|
||||
-webkit-backdrop-filter: blur(8px);
|
||||
backdrop-filter: blur(8px);
|
||||
color: var(--color-font2);
|
||||
font-family: var(--font-sans);
|
||||
font-size: 12.5px;
|
||||
font-weight: 500;
|
||||
line-height: 1;
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.live-pill[hidden] { display: none; }
|
||||
|
||||
.live-pill:hover {
|
||||
border-color: var(--muted);
|
||||
color: var(--color-font1);
|
||||
}
|
||||
|
||||
.live-dot {
|
||||
width: 8px;
|
||||
height: 8px;
|
||||
border-radius: 50%;
|
||||
background: var(--ok);
|
||||
animation: live-pulse 2.4s ease-out infinite;
|
||||
}
|
||||
|
||||
.live-pill[data-state="paused"] .live-dot { background: var(--muted); animation: none; }
|
||||
.live-pill[data-state="retry"] .live-dot { background: var(--warn); animation: none; }
|
||||
|
||||
@keyframes live-pulse {
|
||||
0% { box-shadow: 0 0 0 0 rgba(110, 219, 154, 0.45); }
|
||||
70%, 100% { box-shadow: 0 0 0 7px rgba(110, 219, 154, 0); }
|
||||
}
|
||||
|
||||
/* Whatever just changed gets a brief outline that fades away */
|
||||
|
||||
.live-flash { animation: live-flash 1.4s ease-out; }
|
||||
|
||||
@keyframes live-flash {
|
||||
0% { outline: 2px solid rgba(110, 219, 154, 0.65); outline-offset: -2px; }
|
||||
100% { outline: 2px solid rgba(110, 219, 154, 0); outline-offset: -2px; }
|
||||
}
|
||||
|
||||
@media (prefers-reduced-motion: reduce) {
|
||||
.live-dot,
|
||||
.live-flash { animation: none; }
|
||||
}
|
||||
|
||||
@media (max-width: 640px) {
|
||||
.live-pill { right: 10px; bottom: 10px; }
|
||||
}
|
||||
@@ -0,0 +1,325 @@
|
||||
/* OpenBench live updates: the pages keep themselves current.
|
||||
|
||||
Every few seconds the page asks the server for its own HTML, and only the
|
||||
parts that changed are swapped in. Scroll position, text selection, open
|
||||
forms and the LLR history graph are left alone. Polling pauses in a hidden
|
||||
tab, backs off when the server is unreachable, and can be switched off with
|
||||
the pill in the corner. No dependencies, and the pages work without it. */
|
||||
|
||||
(function () {
|
||||
'use strict';
|
||||
|
||||
var PAGES = /^\/(?:(?:index|greens|machines|events|errors)(?:\/\d+)?|user\/[^\/]+(?:\/\d+)?|(?:test|tune|datagen)\/\d+)?\/?$/;
|
||||
if (!PAGES.test(window.location.pathname)) return;
|
||||
|
||||
var content = document.getElementById('content');
|
||||
if (!content || !window.fetch || !window.DOMParser) return;
|
||||
|
||||
var FULL = { year: 'numeric', month: '2-digit', day: '2-digit', hour: '2-digit', minute: '2-digit', second: '2-digit', hour12: false };
|
||||
var DAY = { month: 'short', day: '2-digit' };
|
||||
|
||||
// Never replaced: forms keep what is typed, banners can be dismissed, the graphs load themselves.
|
||||
// The SPSA chart and parameter list ( Tune pages ) are interactive, so their scripts refresh them
|
||||
// from the 'live:patched' event instead.
|
||||
var PROTECT = 'form, .banner, .llr-history-panel, .spsa-chart, #spsa-rows, #spsa-empty, [data-live-skip], script, style';
|
||||
|
||||
// Attributes that other scripts, or the reader, add after the page loads ( 'open' is a fold the reader opened )
|
||||
var KEEP = { 'data-href': true, 'data-epoch': true, 'open': true };
|
||||
|
||||
/* ---------- Timestamps ----------
|
||||
The pages print raw epochs and the browser formats them. Remember the
|
||||
epoch before that happens, so that two versions can be compared. */
|
||||
|
||||
function stash(root) {
|
||||
Array.prototype.forEach.call(root.querySelectorAll('.timestamp, .datestamp'), function (el) {
|
||||
var text = el.textContent.trim();
|
||||
if (!el.hasAttribute('data-epoch') && /^\d+(\.\d+)?$/.test(text)) el.setAttribute('data-epoch', text);
|
||||
});
|
||||
}
|
||||
|
||||
function formatStamp(el) {
|
||||
var epoch = parseFloat(el.getAttribute('data-epoch'));
|
||||
if (isNaN(epoch)) return;
|
||||
el.textContent = new Date(1000 * epoch).toLocaleString(undefined, el.classList.contains('datestamp') ? DAY : FULL);
|
||||
}
|
||||
|
||||
function isStamp(el) {
|
||||
return el.classList.contains('timestamp') || el.classList.contains('datestamp');
|
||||
}
|
||||
|
||||
stash(content);
|
||||
|
||||
/* ---------- Patching ---------- */
|
||||
|
||||
function flash(el) {
|
||||
if (!el || el.nodeType !== 1) return;
|
||||
el.classList.remove('live-flash');
|
||||
void el.offsetWidth;
|
||||
el.classList.add('live-flash');
|
||||
setTimeout(function () { el.classList.remove('live-flash'); }, 1500);
|
||||
}
|
||||
|
||||
function protectedNode(node) {
|
||||
return node.nodeType === 1 && node.matches(PROTECT);
|
||||
}
|
||||
|
||||
function kids(el) {
|
||||
return Array.prototype.filter.call(el.childNodes, function (child) {
|
||||
if (child.nodeType === 3) return child.nodeValue.trim() !== '';
|
||||
return child.nodeType === 1 && !protectedNode(child);
|
||||
});
|
||||
}
|
||||
|
||||
function same(a, b) {
|
||||
if (a.nodeType !== b.nodeType) return false;
|
||||
return a.nodeType !== 1 || a.tagName === b.tagName;
|
||||
}
|
||||
|
||||
function syncAttributes(o, n) {
|
||||
|
||||
var i, attr;
|
||||
|
||||
for (i = 0; i < n.attributes.length; i++) {
|
||||
attr = n.attributes[i];
|
||||
if (attr.name === 'class') continue;
|
||||
if (o.getAttribute(attr.name) !== attr.value) o.setAttribute(attr.name, attr.value);
|
||||
}
|
||||
|
||||
for (i = o.attributes.length - 1; i >= 0; i--) {
|
||||
attr = o.attributes[i];
|
||||
if (attr.name === 'class' || KEEP[attr.name]) continue;
|
||||
if (!n.hasAttribute(attr.name)) o.removeAttribute(attr.name);
|
||||
}
|
||||
|
||||
// Classes come from the server, except the highlight this script adds
|
||||
var wanted = (n.getAttribute('class') || '') + (o.classList.contains('live-flash') ? ' live-flash' : '');
|
||||
if ((o.getAttribute('class') || '') !== wanted) {
|
||||
if (wanted.trim()) o.setAttribute('class', wanted);
|
||||
else o.removeAttribute('class');
|
||||
}
|
||||
}
|
||||
|
||||
function patchNode(o, n) {
|
||||
|
||||
if (o.nodeType === 3) {
|
||||
if (o.nodeValue !== n.nodeValue) {
|
||||
o.nodeValue = n.nodeValue;
|
||||
flash(o.parentNode);
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
if (o.nodeType !== 1 || protectedNode(o)) return;
|
||||
|
||||
if (isStamp(o)) {
|
||||
if (o.getAttribute('data-epoch') !== n.getAttribute('data-epoch')) {
|
||||
var fresh = document.importNode(n, true);
|
||||
formatStamp(fresh);
|
||||
o.parentNode.replaceChild(fresh, o);
|
||||
flash(fresh);
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
syncAttributes(o, n);
|
||||
patchChildren(o, n);
|
||||
}
|
||||
|
||||
/* Children are matched from both ends, and only what is left in the
|
||||
middle is replaced. A row that appears, or a button that disappears,
|
||||
leaves the rest of its parent untouched. */
|
||||
|
||||
function patchChildren(oldEl, newEl) {
|
||||
|
||||
var o = kids(oldEl), n = kids(newEl);
|
||||
var start = 0, oe = o.length, ne = n.length, i;
|
||||
|
||||
while (start < oe && start < ne && same(o[start], n[start])) {
|
||||
patchNode(o[start], n[start]);
|
||||
start++;
|
||||
}
|
||||
|
||||
while (oe > start && ne > start && same(o[oe - 1], n[ne - 1])) {
|
||||
oe--; ne--;
|
||||
patchNode(o[oe], n[ne]);
|
||||
}
|
||||
|
||||
if (start === oe && start === ne) return;
|
||||
|
||||
var before = o[oe] || null;
|
||||
|
||||
for (i = start; i < oe; i++) oldEl.removeChild(o[i]);
|
||||
|
||||
for (i = start; i < ne; i++) {
|
||||
var node = document.importNode(n[i], true);
|
||||
if (node.nodeType === 1) {
|
||||
Array.prototype.forEach.call(node.querySelectorAll('.timestamp, .datestamp'), formatStamp);
|
||||
if (isStamp(node)) formatStamp(node);
|
||||
}
|
||||
oldEl.insertBefore(node, before);
|
||||
flash(node.nodeType === 1 ? node : oldEl);
|
||||
}
|
||||
}
|
||||
|
||||
// ux.js makes whole rows clickable once, when the page loads
|
||||
function restoreRows() {
|
||||
Array.prototype.forEach.call(content.querySelectorAll('table.test-list tbody tr'), function (row) {
|
||||
var link = row.querySelector('.col-test a');
|
||||
if (link && !row.getAttribute('data-href')) row.setAttribute('data-href', link.getAttribute('href'));
|
||||
});
|
||||
}
|
||||
|
||||
function apply(html) {
|
||||
|
||||
var doc = new DOMParser().parseFromString(html, 'text/html');
|
||||
var fresh = doc.getElementById('content');
|
||||
if (!fresh) return false;
|
||||
|
||||
stash(fresh);
|
||||
patchChildren(content, fresh);
|
||||
restoreRows();
|
||||
|
||||
// Scripts that own a part of the page that is never patched ( see PROTECT ) refresh it from here
|
||||
document.dispatchEvent(new CustomEvent('live:patched', { detail: { fresh: fresh } }));
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
/* ---------- The indicator ---------- */
|
||||
|
||||
var pill = document.createElement('button');
|
||||
pill.type = 'button';
|
||||
pill.id = 'live-indicator';
|
||||
pill.className = 'live-pill';
|
||||
pill.innerHTML = '<span class="live-dot" aria-hidden="true"></span><span class="live-text">Live</span>';
|
||||
document.body.appendChild(pill);
|
||||
|
||||
var enabled = true;
|
||||
try { enabled = window.localStorage.getItem('ob:live') !== 'off'; } catch (error) { /* storage unavailable */ }
|
||||
|
||||
var timer = null, busy = false, failures = 0, last = Date.now(), dead = false;
|
||||
|
||||
function setState(state) {
|
||||
|
||||
var label = { live: 'Live', paused: 'Paused', retry: 'Reconnecting' }[state];
|
||||
pill.setAttribute('data-state', state);
|
||||
pill.setAttribute('aria-pressed', String(enabled));
|
||||
pill.querySelector('.live-text').textContent = label;
|
||||
|
||||
pill.title = state === 'paused'
|
||||
? 'Automatic updates are off. Click to turn them on.'
|
||||
: 'Updated ' + new Date(last).toLocaleTimeString() + '. Click to pause.';
|
||||
}
|
||||
|
||||
/* ---------- Polling ---------- */
|
||||
|
||||
function running() {
|
||||
return !!document.querySelector('.page-head .fa-spin');
|
||||
}
|
||||
|
||||
function interval() {
|
||||
|
||||
var path = window.location.pathname, base = 10000;
|
||||
|
||||
if (/^\/(test|tune|datagen)\//.test(path)) base = document.querySelector('.page-head .fa-spin') ? 8000 : 45000;
|
||||
else if (/^\/(events|errors)/.test(path)) base = 20000;
|
||||
|
||||
return base * Math.pow(2, Math.min(failures, 3));
|
||||
}
|
||||
|
||||
// Leave the page alone while somebody is reading, selecting or typing
|
||||
function occupied() {
|
||||
|
||||
var selection = window.getSelection && window.getSelection();
|
||||
if (selection && !selection.isCollapsed && selection.anchorNode && content.contains(selection.anchorNode)) return true;
|
||||
|
||||
var focused = document.activeElement;
|
||||
if (focused && content.contains(focused) && /^(INPUT|TEXTAREA|SELECT)$/.test(focused.tagName)) return true;
|
||||
|
||||
var palette = document.getElementById('palette');
|
||||
return !!(palette && !palette.hidden);
|
||||
}
|
||||
|
||||
function schedule(delay) {
|
||||
clearTimeout(timer);
|
||||
if (!enabled || dead || document.hidden) return;
|
||||
timer = setTimeout(tick, delay === undefined ? interval() : delay);
|
||||
}
|
||||
|
||||
function tick() {
|
||||
if (document.hidden) return;
|
||||
if (occupied()) { schedule(3000); return; }
|
||||
poll();
|
||||
}
|
||||
|
||||
function strip(path) { return path.replace(/\/+$/, ''); }
|
||||
|
||||
function poll() {
|
||||
|
||||
if (busy) return;
|
||||
busy = true;
|
||||
|
||||
var path = window.location.pathname;
|
||||
|
||||
fetch(window.location.pathname + window.location.search, {
|
||||
credentials : 'same-origin',
|
||||
cache : 'no-store',
|
||||
headers : { 'Accept': 'text/html' }
|
||||
})
|
||||
.then(function (response) {
|
||||
|
||||
// Sent somewhere else ( a login page, or another kind of workload ): stop quietly
|
||||
if (response.redirected && strip(new URL(response.url).pathname) !== strip(path)) {
|
||||
dead = true;
|
||||
throw new Error('moved');
|
||||
}
|
||||
|
||||
if (!response.ok) throw new Error('status ' + response.status);
|
||||
return response.text();
|
||||
})
|
||||
.then(function (html) {
|
||||
|
||||
// A test that has just finished still has a last data point to draw
|
||||
var wasRunning = running();
|
||||
|
||||
if (!apply(html)) throw new Error('no content');
|
||||
|
||||
if (window.refreshLLRHistory && (wasRunning || running())) window.refreshLLRHistory();
|
||||
failures = 0;
|
||||
last = Date.now();
|
||||
setState('live');
|
||||
})
|
||||
.catch(function () {
|
||||
failures++;
|
||||
if (dead) pill.hidden = true;
|
||||
else setState('retry');
|
||||
})
|
||||
.then(function () {
|
||||
busy = false;
|
||||
schedule();
|
||||
});
|
||||
}
|
||||
|
||||
pill.addEventListener('click', function () {
|
||||
|
||||
enabled = !enabled;
|
||||
try { window.localStorage.setItem('ob:live', enabled ? 'on' : 'off'); } catch (error) { /* ignore */ }
|
||||
|
||||
if (enabled) { setState('live'); poll(); }
|
||||
else { clearTimeout(timer); setState('paused'); }
|
||||
});
|
||||
|
||||
document.addEventListener('visibilitychange', function () {
|
||||
|
||||
if (document.hidden) { clearTimeout(timer); return; }
|
||||
if (!enabled || dead) return;
|
||||
|
||||
// Coming back to the tab: catch up at once, unless it was just done
|
||||
if (Date.now() - last > 4000) poll();
|
||||
else schedule();
|
||||
});
|
||||
|
||||
setState(enabled ? 'live' : 'paused');
|
||||
schedule();
|
||||
|
||||
})();
|
||||
@@ -269,6 +269,25 @@
|
||||
this.setActive(this.active);
|
||||
};
|
||||
|
||||
/* Live updates: take a newer answer from the server and redraw in place.
|
||||
The plot, and whichever point is being inspected, stay where they are. */
|
||||
|
||||
Graph.prototype.update = function (data) {
|
||||
|
||||
this.lower = Number(data.lower);
|
||||
this.upper = Number(data.upper);
|
||||
this.games = Number(data.games);
|
||||
|
||||
this.points = data.history.map(function (p) {
|
||||
return { games: Number(p[0]), llr: Number(p[1]), estimated: !!p[2] };
|
||||
}).sort(function (a, b) { return a.games - b.games; });
|
||||
|
||||
if (this.active >= this.points.length)
|
||||
this.active = -1;
|
||||
|
||||
this.render();
|
||||
};
|
||||
|
||||
/* ---------- snapping ---------- */
|
||||
|
||||
Graph.prototype.pick = function (x) {
|
||||
@@ -417,13 +436,45 @@
|
||||
if (!node)
|
||||
return showError(container, 'No history to show yet.');
|
||||
|
||||
new Graph(node, JSON.parse(node.getAttribute('data-chart')));
|
||||
graph = new Graph(node, JSON.parse(node.getAttribute('data-chart')));
|
||||
|
||||
}).catch(function () {
|
||||
showError(container, 'Unable to load history graph.');
|
||||
});
|
||||
}
|
||||
|
||||
var graph = null;
|
||||
|
||||
function refresh(container) {
|
||||
|
||||
var url = container.getAttribute('data-history-url');
|
||||
if (!url || !graph)
|
||||
return Promise.resolve();
|
||||
|
||||
return fetch(url, { credentials: 'same-origin', cache: 'no-store' }).then(function (response) {
|
||||
|
||||
if (!response.ok)
|
||||
throw new Error('Unable to refresh history graph');
|
||||
|
||||
return response.text();
|
||||
|
||||
}).then(function (markup) {
|
||||
|
||||
var holder = document.createElement('div');
|
||||
holder.innerHTML = markup;
|
||||
|
||||
var node = holder.querySelector('.llr-chart');
|
||||
if (node)
|
||||
graph.update(JSON.parse(node.getAttribute('data-chart')));
|
||||
});
|
||||
}
|
||||
|
||||
// Called by live.js whenever the page has been brought up to date
|
||||
window.refreshLLRHistory = function () {
|
||||
var container = document.getElementById('llr-history-container');
|
||||
return container ? refresh(container).catch(function () { /* keep the current graph */ }) : Promise.resolve();
|
||||
};
|
||||
|
||||
document.addEventListener('DOMContentLoaded', function () {
|
||||
var container = document.getElementById('llr-history-container');
|
||||
if (container)
|
||||
|
||||
+21
-130
@@ -1,133 +1,24 @@
|
||||
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
|
||||
<svg
|
||||
xmlns:dc="http://purl.org/dc/elements/1.1/"
|
||||
xmlns:cc="http://creativecommons.org/ns#"
|
||||
xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
|
||||
xmlns:svg="http://www.w3.org/2000/svg"
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
xmlns:sodipodi="http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd"
|
||||
xmlns:inkscape="http://www.inkscape.org/namespaces/inkscape"
|
||||
width="250mm"
|
||||
height="250mm"
|
||||
viewBox="0 0 250 250"
|
||||
version="1.1"
|
||||
id="svg8"
|
||||
inkscape:version="1.0 (4035a4f, 2020-05-01)"
|
||||
sodipodi:docname="logo.svg">
|
||||
<defs
|
||||
id="defs2">
|
||||
<inkscape:perspective
|
||||
sodipodi:type="inkscape:persp3d"
|
||||
inkscape:vp_x="-192.73904 : 85.416586 : 1"
|
||||
inkscape:vp_y="0 : 999.99996 : 0"
|
||||
inkscape:vp_z="210 : 101.5 : 1"
|
||||
inkscape:persp3d-origin="105 : 51.999997 : 1"
|
||||
id="perspective857" />
|
||||
<rect
|
||||
x="191.06123"
|
||||
y="167.60974"
|
||||
width="9.3152771"
|
||||
height="28.649736"
|
||||
id="rect853" />
|
||||
<rect
|
||||
x="120.10982"
|
||||
y="27.845661"
|
||||
width="83.140968"
|
||||
height="150.35945"
|
||||
id="rect24" />
|
||||
<rect
|
||||
x="113.84743"
|
||||
y="28.873098"
|
||||
width="68.721581"
|
||||
height="89.834076"
|
||||
id="rect18" />
|
||||
<rect
|
||||
x="37.502277"
|
||||
y="98.018333"
|
||||
width="79.874741"
|
||||
height="106.64691"
|
||||
id="rect12" />
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 250 250" width="250" height="250">
|
||||
<title>OpenBench</title>
|
||||
<defs>
|
||||
<clipPath id="tile">
|
||||
<rect width="250" height="250" rx="48"/>
|
||||
</clipPath>
|
||||
</defs>
|
||||
<sodipodi:namedview
|
||||
id="base"
|
||||
pagecolor="#ffffff"
|
||||
bordercolor="#666666"
|
||||
borderopacity="1.0"
|
||||
inkscape:pageopacity="0.0"
|
||||
inkscape:pageshadow="2"
|
||||
inkscape:zoom="1"
|
||||
inkscape:cx="509.11884"
|
||||
inkscape:cy="432.95515"
|
||||
inkscape:document-units="mm"
|
||||
inkscape:current-layer="layer1"
|
||||
inkscape:document-rotation="0"
|
||||
showgrid="false"
|
||||
fit-margin-top="0"
|
||||
fit-margin-left="0"
|
||||
fit-margin-right="0"
|
||||
fit-margin-bottom="0"
|
||||
inkscape:snap-bbox="false"
|
||||
inkscape:window-width="1853"
|
||||
inkscape:window-height="1025"
|
||||
inkscape:window-x="67"
|
||||
inkscape:window-y="27"
|
||||
inkscape:window-maximized="1" />
|
||||
<metadata
|
||||
id="metadata5">
|
||||
<rdf:RDF>
|
||||
<cc:Work
|
||||
rdf:about="">
|
||||
<dc:format>image/svg+xml</dc:format>
|
||||
<dc:type
|
||||
rdf:resource="http://purl.org/dc/dcmitype/StillImage" />
|
||||
<dc:title></dc:title>
|
||||
</cc:Work>
|
||||
</rdf:RDF>
|
||||
</metadata>
|
||||
<g
|
||||
inkscape:label="Layer 1"
|
||||
inkscape:groupmode="layer"
|
||||
id="layer1"
|
||||
transform="translate(16.1122,-26.054426)">
|
||||
<rect
|
||||
style="fill:#94e196;fill-opacity:1;stroke-width:0.264583"
|
||||
id="rect873"
|
||||
width="250"
|
||||
height="250"
|
||||
x="-16.1122"
|
||||
y="26.054426" />
|
||||
<g
|
||||
id="g949">
|
||||
<rect
|
||||
y="26.054426"
|
||||
x="-16.1122"
|
||||
height="125"
|
||||
width="125"
|
||||
id="rect875"
|
||||
style="fill:#118c40;fill-opacity:1;stroke-width:0.264583" />
|
||||
<rect
|
||||
style="fill:#118c40;fill-opacity:1;stroke-width:0.264583"
|
||||
id="rect875-3"
|
||||
width="125"
|
||||
height="125"
|
||||
x="108.88778"
|
||||
y="151.05443" />
|
||||
</g>
|
||||
<text
|
||||
xml:space="preserve"
|
||||
id="text16"
|
||||
style="font-style:normal;font-weight:normal;font-size:10.5833px;line-height:1.25;font-family:sans-serif;white-space:pre;shape-inside:url(#rect18);fill:#000000;fill-opacity:1;stroke:none;" />
|
||||
<path
|
||||
id="path860"
|
||||
style="font-style:normal;font-variant:normal;font-weight:bold;font-stretch:normal;font-size:88.1944px;line-height:1.25;font-family:sans-serif;-inkscape-font-specification:'sans-serif Bold';white-space:pre;fill:#0d0208;fill-opacity:1;stroke:none;stroke-width:3.24563"
|
||||
d="m 108.88778,78.418988 q -23.454412,0 -36.380997,19.056735 -12.926584,19.056717 -12.926584,53.651967 0,34.4487 12.926584,53.50539 12.926585,19.05675 36.380997,19.05675 23.5877,0 36.51428,-19.05675 12.92658,-19.05669 12.92658,-53.50539 0,-34.59525 -12.92658,-53.651967 -12.92658,-19.056735 -36.51428,-19.056735 z m 0,-40.898628 q 47.97497,0 75.16077,30.197581 27.18582,30.197552 27.18582,83.409749 0,53.06564 -27.18582,83.26322 -27.1858,30.19758 -75.16077,30.19758 -47.841678,0 -75.16075,-30.19758 Q 6.5412263,204.19333 6.5412263,151.12769 6.5412263,97.915493 33.72703,67.717941 61.046102,37.52036 108.88778,37.52036 Z" />
|
||||
<path
|
||||
id="path863"
|
||||
style="font-style:normal;font-variant:normal;font-weight:bold;font-stretch:normal;font-size:105.833px;line-height:1.25;font-family:sans-serif;-inkscape-font-specification:'sans-serif Bold';white-space:pre;fill:#008f11;fill-opacity:1;stroke:none;stroke-width:2.06305"
|
||||
d="m -87.315338,146.28255 q 9.70158,0 14.71229,-4.26443 5.0107,-4.26443 5.0107,-12.58006 0,-8.20903 -5.0107,-12.47346 -5.01071,-4.37104 -14.71229,-4.37104 h -22.708072 v 33.68899 z m 1.38594,69.6168 q 12.36685,0 18.55028,-5.22393 6.29004,-5.22391 6.29004,-15.77838 0,-10.34124 -6.18344,-15.45855 -6.18341,-5.22393 -18.65688,-5.22393 h -24.094012 v 41.68479 z m 38.16665,-57.24996 q 13.21974,3.83799 20.46925,14.17923 7.24954,10.34124 7.24954,25.37335 0,23.02791 -15.56518,34.32866 -15.56515,11.30073 -47.33515,11.30073 H -151.06855 V 84.661543 h 61.621012 q 33.15594,0 47.97482,10.02141 14.92551,10.021417 14.92551,32.089837 0,11.62057 -5.43715,19.82959 -5.43714,8.10242 -15.77839,12.04701 z" />
|
||||
<text
|
||||
xml:space="preserve"
|
||||
id="text851"
|
||||
style="font-style:normal;font-weight:normal;font-size:10.5833px;line-height:1.25;font-family:sans-serif;white-space:pre;shape-inside:url(#rect853);fill:#000000;fill-opacity:1;stroke:none;" />
|
||||
|
||||
<!-- Board: graphite base, accent-green and surface-grey squares -->
|
||||
<g clip-path="url(#tile)">
|
||||
<rect width="250" height="250" fill="#14161A"/>
|
||||
<rect x="0" y="0" width="125" height="125" fill="#4F8160"/>
|
||||
<rect x="125" y="125" width="125" height="125" fill="#4F8160"/>
|
||||
<rect x="125" y="0" width="125" height="125" fill="#23272D"/>
|
||||
<rect x="0" y="125" width="125" height="125" fill="#23272D"/>
|
||||
</g>
|
||||
|
||||
<!-- Thin rim so the tile stays defined on dark browser chrome -->
|
||||
<rect x="1.5" y="1.5" width="247" height="247" rx="46.5" fill="none" stroke="#3A3F48" stroke-width="3"/>
|
||||
|
||||
<!-- O, in the theme's bone text colour -->
|
||||
<circle cx="125" cy="125" r="62" fill="none" stroke="#EDEAE3" stroke-width="32"/>
|
||||
</svg>
|
||||
|
Before Width: | Height: | Size: 5.5 KiB After Width: | Height: | Size: 1008 B |
@@ -0,0 +1,286 @@
|
||||
/* ==========================================================================
|
||||
Quick search ( Ctrl+K ): a Spotlight-style palette.
|
||||
Loaded after refresh.css, and uses its tokens.
|
||||
========================================================================== */
|
||||
|
||||
html.palette-open { overflow: hidden; }
|
||||
|
||||
/* The shortcut hint inside the top bar button */
|
||||
|
||||
.topbar-kbd {
|
||||
margin-left: 8px;
|
||||
padding: 1px 6px;
|
||||
border: 1px solid var(--line-strong);
|
||||
border-radius: 5px;
|
||||
color: var(--muted);
|
||||
font-family: var(--font-mono, ui-monospace, "JetBrains Mono", SFMono-Regular, Menlo, monospace);
|
||||
font-size: 11px;
|
||||
line-height: 1.5;
|
||||
}
|
||||
|
||||
@media (hover: none), (max-width: 900px) {
|
||||
.topbar-kbd { display: none; }
|
||||
}
|
||||
|
||||
/* Overlay */
|
||||
|
||||
#palette {
|
||||
position: fixed;
|
||||
inset: 0;
|
||||
z-index: 1000;
|
||||
display: flex;
|
||||
justify-content: center;
|
||||
align-items: flex-start;
|
||||
padding: 13vh 16px 16px;
|
||||
}
|
||||
|
||||
#palette[hidden] { display: none; }
|
||||
|
||||
.pl-backdrop {
|
||||
position: absolute;
|
||||
inset: 0;
|
||||
background: rgba(8, 9, 11, 0.55);
|
||||
-webkit-backdrop-filter: blur(6px);
|
||||
backdrop-filter: blur(6px);
|
||||
}
|
||||
|
||||
/* Panel */
|
||||
|
||||
.pl-panel {
|
||||
position: relative;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
width: min(660px, 100%);
|
||||
max-height: min(70vh, 560px);
|
||||
overflow: hidden;
|
||||
background: rgba(31, 34, 39, 0.9);
|
||||
-webkit-backdrop-filter: blur(28px) saturate(1.4);
|
||||
backdrop-filter: blur(28px) saturate(1.4);
|
||||
border: 1px solid rgba(237, 234, 227, 0.1);
|
||||
border-radius: 14px;
|
||||
box-shadow: 0 24px 70px rgba(0, 0, 0, 0.55), 0 0 0 0.5px rgba(0, 0, 0, 0.6);
|
||||
}
|
||||
|
||||
@supports not ((backdrop-filter: blur(1px)) or (-webkit-backdrop-filter: blur(1px))) {
|
||||
.pl-panel { background: #1F2227; }
|
||||
}
|
||||
|
||||
/* Search field: big and quiet, like the one on macOS */
|
||||
|
||||
.pl-field {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 14px;
|
||||
padding: 16px 20px;
|
||||
}
|
||||
|
||||
.pl-glass {
|
||||
flex: none;
|
||||
color: var(--muted);
|
||||
font-size: 18px;
|
||||
}
|
||||
|
||||
#palette input.pl-input {
|
||||
flex: 1;
|
||||
width: 100%;
|
||||
height: auto;
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
background: transparent;
|
||||
border: 0;
|
||||
border-radius: 0;
|
||||
box-shadow: none;
|
||||
outline: none;
|
||||
color: var(--color-font1);
|
||||
font-family: inherit;
|
||||
font-size: 20px;
|
||||
font-weight: 400;
|
||||
line-height: 1.3;
|
||||
}
|
||||
|
||||
#palette input.pl-input::placeholder { color: var(--muted); opacity: 1; }
|
||||
|
||||
/* Results */
|
||||
|
||||
.pl-list {
|
||||
flex: 1 1 auto;
|
||||
min-height: 0;
|
||||
margin: 0;
|
||||
padding: 6px 8px 8px;
|
||||
list-style: none;
|
||||
overflow-y: auto;
|
||||
overscroll-behavior: contain;
|
||||
border-top: 1px solid var(--line);
|
||||
}
|
||||
|
||||
.pl-group {
|
||||
padding: 10px 12px 4px;
|
||||
color: var(--muted);
|
||||
font-size: 12px;
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
.pl-group:first-child { padding-top: 6px; }
|
||||
|
||||
.pl-item {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 12px;
|
||||
padding: 7px 10px;
|
||||
border-radius: 9px;
|
||||
color: var(--color-font1);
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.pl-icon {
|
||||
flex: none;
|
||||
display: grid;
|
||||
place-items: center;
|
||||
width: 30px;
|
||||
height: 30px;
|
||||
border-radius: 8px;
|
||||
background: var(--accent-soft);
|
||||
color: var(--accent-hover);
|
||||
font-size: 14px;
|
||||
}
|
||||
|
||||
.pl-text {
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 1px;
|
||||
}
|
||||
|
||||
.pl-title {
|
||||
overflow: hidden;
|
||||
white-space: nowrap;
|
||||
text-overflow: ellipsis;
|
||||
font-size: 15px;
|
||||
line-height: 1.3;
|
||||
}
|
||||
|
||||
.pl-title b { font-weight: 700; }
|
||||
|
||||
.pl-sub {
|
||||
overflow: hidden;
|
||||
white-space: nowrap;
|
||||
text-overflow: ellipsis;
|
||||
color: var(--muted);
|
||||
font-size: 12.5px;
|
||||
line-height: 1.3;
|
||||
}
|
||||
|
||||
.pl-ext {
|
||||
flex: none;
|
||||
color: var(--muted);
|
||||
font-size: 11px;
|
||||
}
|
||||
|
||||
/* A test's verdict */
|
||||
|
||||
.pl-chip {
|
||||
flex: none;
|
||||
padding: 2px 9px;
|
||||
border-radius: 999px;
|
||||
background: rgba(237, 234, 227, 0.08);
|
||||
color: var(--color-font2);
|
||||
font-size: 11.5px;
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
.pl-chip[data-state="passed"] { background: rgba(110, 219, 154, 0.14); color: var(--ok); }
|
||||
.pl-chip[data-state="failed"] { background: rgba(239, 123, 114, 0.14); color: var(--bad); }
|
||||
.pl-chip[data-state="running"] { background: var(--accent-soft); color: var(--accent-hover); }
|
||||
.pl-chip[data-state="pending"],
|
||||
.pl-chip[data-state="awaiting"] { background: rgba(233, 178, 76, 0.14); color: var(--warn); }
|
||||
.pl-chip[data-state="stopped"] {
|
||||
background-image: repeating-linear-gradient(135deg, transparent 0, transparent 4px, rgba(237, 234, 227, 0.14) 4px, rgba(237, 234, 227, 0.14) 5.5px);
|
||||
}
|
||||
|
||||
.pl-enter {
|
||||
display: none;
|
||||
flex: none;
|
||||
margin-left: 2px;
|
||||
font-family: inherit;
|
||||
font-size: 14px;
|
||||
opacity: 0.9;
|
||||
}
|
||||
|
||||
/* The row Enter would open: filled like a selection on macOS */
|
||||
|
||||
.pl-item[aria-selected="true"] {
|
||||
background: var(--accent);
|
||||
color: #fff;
|
||||
}
|
||||
|
||||
.pl-item[aria-selected="true"] .pl-icon { background: rgba(255, 255, 255, 0.18); color: #fff; }
|
||||
.pl-item[aria-selected="true"] .pl-sub,
|
||||
.pl-item[aria-selected="true"] .pl-ext { color: rgba(255, 255, 255, 0.95); }
|
||||
.pl-item[aria-selected="true"] .pl-chip { background: rgba(255, 255, 255, 0.2); background-image: none; color: #fff; }
|
||||
.pl-item[aria-selected="true"] .pl-enter { display: block; }
|
||||
|
||||
/* Footer with the keys */
|
||||
|
||||
.pl-foot {
|
||||
display: flex;
|
||||
gap: 18px;
|
||||
padding: 9px 16px;
|
||||
border-top: 1px solid var(--line);
|
||||
color: var(--muted);
|
||||
font-size: 12px;
|
||||
}
|
||||
|
||||
.pl-foot kbd {
|
||||
display: inline-grid;
|
||||
place-items: center;
|
||||
min-width: 20px;
|
||||
height: 20px;
|
||||
margin-right: 6px;
|
||||
padding: 0 5px;
|
||||
border: 1px solid var(--line);
|
||||
border-radius: 5px;
|
||||
background: rgba(237, 234, 227, 0.08);
|
||||
color: var(--color-font2);
|
||||
font-family: var(--font-sans);
|
||||
font-size: 11px;
|
||||
font-weight: 500;
|
||||
line-height: 1;
|
||||
}
|
||||
|
||||
.pl-foot kbd + kbd { margin-left: -2px; }
|
||||
|
||||
.pl-sr {
|
||||
position: absolute;
|
||||
width: 1px;
|
||||
height: 1px;
|
||||
overflow: hidden;
|
||||
clip: rect(0 0 0 0);
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
/* Motion: only when the palette is opened, and never for people who ask for less */
|
||||
|
||||
@keyframes pl-panel-in {
|
||||
from { opacity: 0; transform: translateY(-8px) scale(0.985); }
|
||||
to { opacity: 1; transform: none; }
|
||||
}
|
||||
|
||||
@keyframes pl-fade-in {
|
||||
from { opacity: 0; }
|
||||
to { opacity: 1; }
|
||||
}
|
||||
|
||||
#palette.is-open .pl-panel { animation: pl-panel-in 0.16s cubic-bezier(0.2, 0.8, 0.2, 1); }
|
||||
#palette.is-open .pl-backdrop { animation: pl-fade-in 0.16s ease-out; }
|
||||
|
||||
@media (prefers-reduced-motion: reduce) {
|
||||
#palette.is-open .pl-panel,
|
||||
#palette.is-open .pl-backdrop { animation: none; }
|
||||
}
|
||||
|
||||
@media (max-width: 640px) {
|
||||
#palette { padding-top: 8vh; }
|
||||
#palette input.pl-input { font-size: 17px; }
|
||||
.pl-foot { display: none; }
|
||||
}
|
||||
@@ -0,0 +1,462 @@
|
||||
/* OpenBench quick search: a Spotlight-style palette.
|
||||
Opens with Ctrl+K or Cmd+K ( and with / outside of text fields ).
|
||||
No dependencies. Without this file the Search button still opens /search. */
|
||||
|
||||
(function () {
|
||||
'use strict';
|
||||
|
||||
var root = document.getElementById('palette');
|
||||
var source = document.getElementById('palette-source');
|
||||
if (!root || !source) return;
|
||||
|
||||
var input = root.querySelector('.pl-input');
|
||||
var list = root.querySelector('.pl-list');
|
||||
var status = root.querySelector('.pl-sr');
|
||||
var form = document.getElementById('palette-search');
|
||||
var trigger = document.getElementById('palette-open');
|
||||
|
||||
var isMac = /Mac|iPhone|iPad|iPod/i.test(navigator.platform || navigator.userAgent || '');
|
||||
|
||||
var STATES = {
|
||||
passed: 'Passed', failed: 'Failed', stopped: 'Stopped', running: 'Running',
|
||||
pending: 'Pending', awaiting: 'Awaiting', deleted: 'Deleted'
|
||||
};
|
||||
|
||||
/* Pages and actions come from the server, so they follow the login state */
|
||||
|
||||
var pages = Array.prototype.map.call(source.querySelectorAll('li'), function (li) {
|
||||
return {
|
||||
kind : 'link',
|
||||
key : 'page:' + li.getAttribute('data-href'),
|
||||
title : li.textContent.trim(),
|
||||
href : li.getAttribute('data-href'),
|
||||
icon : li.getAttribute('data-icon') || 'fa-arrow-right',
|
||||
group : li.getAttribute('data-group') || 'Go to',
|
||||
keywords : (li.getAttribute('data-keywords') || '').toLowerCase(),
|
||||
featured : li.hasAttribute('data-featured'),
|
||||
external : li.hasAttribute('data-external')
|
||||
};
|
||||
});
|
||||
|
||||
var rows = []; // what is on screen: { item, el }
|
||||
var active = -1;
|
||||
var moved = false; // the person has picked a row themselves
|
||||
var returnTo = null;
|
||||
var cache = {}; // query -> tests from the server
|
||||
var lastTests = []; // the latest answer, shown while the next one loads
|
||||
var inflight = null; // { timer, controller }
|
||||
|
||||
/* ---------- Matching ---------- */
|
||||
|
||||
function match(text, query) {
|
||||
|
||||
if (!query) return { score: 0, hits: [] };
|
||||
|
||||
var t = text.toLowerCase(), q = query.toLowerCase();
|
||||
var at = t.indexOf(q), hits = [], i;
|
||||
|
||||
if (at !== -1) {
|
||||
for (i = 0; i < q.length; i++) hits.push(at + i);
|
||||
var boundary = at === 0 || /[\s\-_\/.]/.test(t.charAt(at - 1));
|
||||
return { score: (at === 0 ? 120 : boundary ? 100 : 70) - Math.min(at, 30), hits: hits };
|
||||
}
|
||||
|
||||
// The letters in order, so that "mch" still finds "Machines"
|
||||
var from = 0, gaps = 0;
|
||||
for (i = 0; i < q.length; i++) {
|
||||
var found = t.indexOf(q.charAt(i), from);
|
||||
if (found === -1) return null;
|
||||
if (hits.length && found !== hits[hits.length - 1] + 1) gaps++;
|
||||
hits.push(found);
|
||||
from = found + 1;
|
||||
}
|
||||
return { score: Math.max(10, 50 - gaps * 8), hits: hits };
|
||||
}
|
||||
|
||||
function liveTests(q) {
|
||||
|
||||
if (cache[q]) return cache[q];
|
||||
|
||||
// Until the answer for this exact query arrives, keep what still fits
|
||||
var needle = q.toLowerCase();
|
||||
return lastTests.filter(function (t) {
|
||||
return (t.name + ' ' + t.author + ' ' + t.engine + ' ' + t.id).toLowerCase().indexOf(needle) !== -1;
|
||||
});
|
||||
}
|
||||
|
||||
/* ---------- What to show ---------- */
|
||||
|
||||
function buildGroups(q) {
|
||||
|
||||
var groups = [], i;
|
||||
|
||||
// Tests: a direct jump for numbers, then whatever the server found
|
||||
var tests = liveTests(q).map(function (t) {
|
||||
var m = match(t.name, q);
|
||||
return {
|
||||
kind: 'link', key: 'test:' + t.id, href: t.url, icon: 'fa-flask',
|
||||
title: t.name, hits: m ? m.hits : [], state: t.status,
|
||||
sub: '#' + t.id + ' by ' + t.author + ', ' + t.tc
|
||||
};
|
||||
});
|
||||
|
||||
var number = /^#?(\d{1,9})$/.exec(q);
|
||||
if (number && !tests.some(function (t) { return t.key === 'test:' + number[1]; })) {
|
||||
tests.unshift({
|
||||
kind: 'link', key: 'test:' + number[1], href: '/test/' + number[1] + '/', icon: 'fa-flask',
|
||||
title: 'Open test #' + number[1], sub: 'Jump straight to it', hits: []
|
||||
});
|
||||
}
|
||||
|
||||
// Pages and actions, grouped as on the server, best group first
|
||||
var buckets = [], byName = {};
|
||||
pages.forEach(function (page) {
|
||||
|
||||
var m = null;
|
||||
if (!q) { if (!page.featured) return; m = { score: 0, hits: [] }; }
|
||||
else {
|
||||
m = match(page.title, q);
|
||||
if (!m && page.keywords.indexOf(q.toLowerCase()) !== -1) m = { score: 35, hits: [] };
|
||||
}
|
||||
if (!m) return;
|
||||
|
||||
var bucket = byName[page.group];
|
||||
if (!bucket) { bucket = byName[page.group] = { label: page.group, best: 0, items: [] }; buckets.push(bucket); }
|
||||
|
||||
bucket.best = Math.max(bucket.best, m.score);
|
||||
bucket.items.push({ item: page, score: m.score, hits: m.hits });
|
||||
});
|
||||
|
||||
var best = 0;
|
||||
if (q) buckets.sort(function (a, b) { return b.best - a.best; });
|
||||
buckets.forEach(function (bucket) {
|
||||
if (q) bucket.items.sort(function (a, b) { return b.score - a.score; });
|
||||
best = Math.max(best, bucket.best);
|
||||
});
|
||||
|
||||
var pageGroups = buckets.map(function (bucket) {
|
||||
return {
|
||||
label: bucket.label,
|
||||
items: bucket.items.map(function (entry) {
|
||||
var item = Object.create(entry.item);
|
||||
item.hits = entry.hits;
|
||||
return item;
|
||||
})
|
||||
};
|
||||
});
|
||||
|
||||
var testGroup = tests.length ? [{ label: 'Tests', items: tests }] : [];
|
||||
|
||||
// A page that starts with what was typed wins, otherwise tests come first
|
||||
groups = (q && best < 100) ? testGroup.concat(pageGroups) : pageGroups.concat(testGroup);
|
||||
|
||||
if (q) {
|
||||
groups.push({ label: 'Search', items: [{
|
||||
kind: 'search', key: 'search', icon: 'fa-magnifying-glass', hits: [],
|
||||
title: 'Search all tests for \u201C' + q + '\u201D', sub: 'Looks through every branch name'
|
||||
}] });
|
||||
}
|
||||
|
||||
return groups;
|
||||
}
|
||||
|
||||
/* ---------- Drawing ---------- */
|
||||
|
||||
function fill(el, text, hits) {
|
||||
|
||||
if (!hits || !hits.length) { el.textContent = text; return; }
|
||||
|
||||
var marked = {}, run = '', on = false, i;
|
||||
hits.forEach(function (h) { marked[h] = true; });
|
||||
|
||||
function flush() {
|
||||
if (!run) return;
|
||||
if (on) { var b = document.createElement('b'); b.textContent = run; el.appendChild(b); }
|
||||
else el.appendChild(document.createTextNode(run));
|
||||
run = '';
|
||||
}
|
||||
|
||||
for (i = 0; i < text.length; i++) {
|
||||
var hit = !!marked[i];
|
||||
if (hit !== on) { flush(); on = hit; }
|
||||
run += text.charAt(i);
|
||||
}
|
||||
flush();
|
||||
}
|
||||
|
||||
function element(tag, className, text) {
|
||||
var el = document.createElement(tag);
|
||||
if (className) el.className = className;
|
||||
if (text) el.textContent = text;
|
||||
return el;
|
||||
}
|
||||
|
||||
function buildRow(item, index) {
|
||||
|
||||
var li = element('li', 'pl-item');
|
||||
li.id = 'pl-opt-' + index;
|
||||
li.setAttribute('role', 'option');
|
||||
li.setAttribute('aria-selected', 'false');
|
||||
li.setAttribute('data-index', index);
|
||||
|
||||
var tile = element('span', 'pl-icon');
|
||||
var icon = element('i', 'fa-solid ' + item.icon);
|
||||
icon.setAttribute('aria-hidden', 'true');
|
||||
tile.appendChild(icon);
|
||||
|
||||
var text = element('span', 'pl-text');
|
||||
var title = element('span', 'pl-title');
|
||||
fill(title, item.title, item.hits);
|
||||
text.appendChild(title);
|
||||
if (item.sub) text.appendChild(element('span', 'pl-sub', item.sub));
|
||||
|
||||
li.appendChild(tile);
|
||||
li.appendChild(text);
|
||||
|
||||
if (item.state) {
|
||||
var chip = element('span', 'pl-chip', STATES[item.state] || item.state);
|
||||
chip.setAttribute('data-state', item.state);
|
||||
li.appendChild(chip);
|
||||
}
|
||||
|
||||
if (item.external) {
|
||||
var out = element('i', 'fa-solid fa-arrow-up-right-from-square pl-ext');
|
||||
out.setAttribute('aria-hidden', 'true');
|
||||
li.appendChild(out);
|
||||
}
|
||||
|
||||
var enter = element('kbd', 'pl-enter', '\u21B5');
|
||||
enter.setAttribute('aria-hidden', 'true');
|
||||
li.appendChild(enter);
|
||||
|
||||
return li;
|
||||
}
|
||||
|
||||
function setActive(index, scroll) {
|
||||
|
||||
if (rows[active]) rows[active].el.setAttribute('aria-selected', 'false');
|
||||
active = index;
|
||||
|
||||
if (!rows[index]) { input.removeAttribute('aria-activedescendant'); return; }
|
||||
|
||||
rows[index].el.setAttribute('aria-selected', 'true');
|
||||
input.setAttribute('aria-activedescendant', rows[index].el.id);
|
||||
|
||||
if (!scroll) return;
|
||||
if (index === 0) list.scrollTop = 0;
|
||||
else rows[index].el.scrollIntoView({ block: 'nearest' });
|
||||
}
|
||||
|
||||
function render() {
|
||||
|
||||
var q = input.value.trim();
|
||||
var keep = moved && rows[active] ? rows[active].item.key : null;
|
||||
|
||||
list.textContent = '';
|
||||
rows = [];
|
||||
|
||||
buildGroups(q).forEach(function (group) {
|
||||
var head = element('li', 'pl-group', group.label);
|
||||
head.setAttribute('role', 'presentation');
|
||||
list.appendChild(head);
|
||||
|
||||
group.items.forEach(function (item) {
|
||||
var el = buildRow(item, rows.length);
|
||||
list.appendChild(el);
|
||||
rows.push({ item: item, el: el });
|
||||
});
|
||||
});
|
||||
|
||||
var next = 0;
|
||||
rows.forEach(function (row, i) { if (keep && row.item.key === keep) next = i; });
|
||||
|
||||
active = -1;
|
||||
setActive(rows.length ? next : -1, false);
|
||||
status.textContent = rows.length + (rows.length === 1 ? ' result' : ' results');
|
||||
}
|
||||
|
||||
/* ---------- Asking the server for tests ---------- */
|
||||
|
||||
function cancel() {
|
||||
if (!inflight) return;
|
||||
if (inflight.timer) clearTimeout(inflight.timer);
|
||||
if (inflight.controller) inflight.controller.abort();
|
||||
inflight = null;
|
||||
}
|
||||
|
||||
function request(q) {
|
||||
|
||||
var controller = window.AbortController ? new AbortController() : null;
|
||||
inflight = { timer: null, controller: controller };
|
||||
|
||||
fetch('/api/quick-search/?q=' + encodeURIComponent(q), {
|
||||
credentials : 'same-origin',
|
||||
headers : { 'Accept': 'application/json' },
|
||||
signal : controller ? controller.signal : undefined
|
||||
})
|
||||
.then(function (response) { return response.ok ? response.json() : { tests: [] }; })
|
||||
.then(function (data) {
|
||||
cache[q] = data.tests || [];
|
||||
lastTests = cache[q];
|
||||
if (input.value.trim() === q) render();
|
||||
})
|
||||
.catch(function () { /* aborted, or offline: pages still work */ });
|
||||
}
|
||||
|
||||
function schedule() {
|
||||
|
||||
cancel();
|
||||
|
||||
var q = input.value.trim();
|
||||
if (!q || cache[q]) return;
|
||||
|
||||
inflight = { timer: setTimeout(function () { request(q); }, 140), controller: null };
|
||||
}
|
||||
|
||||
/* ---------- Opening, closing, choosing ---------- */
|
||||
|
||||
function isOpen() { return !root.hidden; }
|
||||
|
||||
function open() {
|
||||
|
||||
if (isOpen()) return;
|
||||
|
||||
returnTo = document.activeElement;
|
||||
root.hidden = false;
|
||||
|
||||
root.classList.remove('is-open');
|
||||
void root.offsetWidth; // restart the entrance animation
|
||||
root.classList.add('is-open');
|
||||
|
||||
document.documentElement.classList.add('palette-open');
|
||||
if (trigger) trigger.setAttribute('aria-expanded', 'true');
|
||||
|
||||
input.value = '';
|
||||
moved = false;
|
||||
render();
|
||||
input.focus();
|
||||
}
|
||||
|
||||
function close() {
|
||||
|
||||
if (!isOpen()) return;
|
||||
|
||||
cancel();
|
||||
root.hidden = true;
|
||||
root.classList.remove('is-open');
|
||||
document.documentElement.classList.remove('palette-open');
|
||||
if (trigger) trigger.setAttribute('aria-expanded', 'false');
|
||||
|
||||
if (returnTo && returnTo.focus && document.contains(returnTo)) returnTo.focus();
|
||||
}
|
||||
|
||||
function choose(item, newTab) {
|
||||
|
||||
if (item.kind === 'search') {
|
||||
form.querySelector('[name="keywords"]').value = input.value.trim();
|
||||
form.submit();
|
||||
return;
|
||||
}
|
||||
|
||||
if (item.external || newTab) {
|
||||
window.open(item.href, '_blank', 'noopener');
|
||||
close();
|
||||
return;
|
||||
}
|
||||
|
||||
window.location.href = item.href;
|
||||
close();
|
||||
}
|
||||
|
||||
function move(step) {
|
||||
if (!rows.length) return;
|
||||
moved = true;
|
||||
setActive((active + step + rows.length) % rows.length, true);
|
||||
}
|
||||
|
||||
/* ---------- Events ---------- */
|
||||
|
||||
input.addEventListener('input', function () {
|
||||
moved = false;
|
||||
render();
|
||||
schedule();
|
||||
});
|
||||
|
||||
input.addEventListener('keydown', function (event) {
|
||||
|
||||
if (event.isComposing) return;
|
||||
|
||||
if (event.key === 'ArrowDown') { event.preventDefault(); move(1); }
|
||||
else if (event.key === 'ArrowUp') { event.preventDefault(); move(-1); }
|
||||
else if (event.key === 'Tab') { event.preventDefault(); move(event.shiftKey ? -1 : 1); }
|
||||
else if (event.key === 'Enter') {
|
||||
event.preventDefault();
|
||||
if (rows[active]) choose(rows[active].item, event.metaKey || event.ctrlKey);
|
||||
}
|
||||
else if (event.key === 'Escape') { event.preventDefault(); close(); }
|
||||
});
|
||||
|
||||
// Keep the caret in the field while the pointer works on the list
|
||||
list.addEventListener('mousedown', function (event) { event.preventDefault(); });
|
||||
|
||||
list.addEventListener('mousemove', function (event) {
|
||||
var li = event.target.closest ? event.target.closest('.pl-item') : null;
|
||||
if (!li) return;
|
||||
var index = parseInt(li.getAttribute('data-index'), 10);
|
||||
if (index !== active) { moved = true; setActive(index, false); }
|
||||
});
|
||||
|
||||
list.addEventListener('click', function (event) {
|
||||
var li = event.target.closest ? event.target.closest('.pl-item') : null;
|
||||
if (!li) return;
|
||||
var row = rows[parseInt(li.getAttribute('data-index'), 10)];
|
||||
if (row) choose(row.item, event.metaKey || event.ctrlKey);
|
||||
});
|
||||
|
||||
root.querySelector('.pl-backdrop').addEventListener('click', close);
|
||||
|
||||
// Nothing behind the palette should take the focus
|
||||
root.addEventListener('focusin', function (event) {
|
||||
if (!root.querySelector('.pl-panel').contains(event.target)) input.focus();
|
||||
});
|
||||
|
||||
function typing(target) {
|
||||
if (!target || !target.tagName) return false;
|
||||
return /^(INPUT|TEXTAREA|SELECT)$/.test(target.tagName) || target.isContentEditable;
|
||||
}
|
||||
|
||||
document.addEventListener('keydown', function (event) {
|
||||
|
||||
var key = (event.key || '').toLowerCase();
|
||||
|
||||
if ((event.metaKey || event.ctrlKey) && !event.altKey && !event.shiftKey && key === 'k') {
|
||||
event.preventDefault();
|
||||
if (isOpen()) close(); else open();
|
||||
return;
|
||||
}
|
||||
|
||||
if (key === '/' && !event.metaKey && !event.ctrlKey && !event.altKey && !isOpen() && !typing(event.target)) {
|
||||
event.preventDefault();
|
||||
open();
|
||||
}
|
||||
}, true);
|
||||
|
||||
if (trigger) {
|
||||
trigger.setAttribute('aria-haspopup', 'dialog');
|
||||
trigger.setAttribute('aria-expanded', 'false');
|
||||
|
||||
trigger.addEventListener('click', function (event) {
|
||||
if (event.button !== 0 || event.metaKey || event.ctrlKey || event.shiftKey) return;
|
||||
event.preventDefault();
|
||||
open();
|
||||
});
|
||||
}
|
||||
|
||||
// Coming back with the Back button should never show an open palette
|
||||
window.addEventListener('pageshow', function (event) { if (event.persisted) close(); });
|
||||
|
||||
Array.prototype.forEach.call(document.querySelectorAll('.topbar-kbd'), function (hint) {
|
||||
hint.textContent = isMac ? '\u2318K' : 'Ctrl K';
|
||||
});
|
||||
|
||||
})();
|
||||
@@ -0,0 +1,290 @@
|
||||
/* ==========================================================================
|
||||
OpenBench - design refresh
|
||||
|
||||
Loaded last (after style.css, ux.css, board.css). Only overrides tokens and
|
||||
a handful of rules, so the older theme stays intact. Drop the <link> in
|
||||
base.html to revert everything in one step.
|
||||
|
||||
Direction: warm graphite surfaces, bone-coloured text, a single board-green
|
||||
accent. Colour is reserved for results (green / amber / red). The LLR gauge
|
||||
on running SPRT tests is the one distinctive element; the rest stays quiet.
|
||||
========================================================================== */
|
||||
|
||||
:root {
|
||||
/* Surfaces */
|
||||
--color1: #14161A;
|
||||
--color2: #1A1D22;
|
||||
--color3: #23272D;
|
||||
--surface-head: #1F2227;
|
||||
--surface-hover: #252A30;
|
||||
|
||||
/* Lines */
|
||||
--line: #2A2E35;
|
||||
--line-strong: #3A3F48;
|
||||
|
||||
/* Text */
|
||||
--color-font1: #EDEAE3;
|
||||
--color-font2: #C9C6BE;
|
||||
--color-font3: #A9CDB3;
|
||||
--muted: #8C8F96;
|
||||
|
||||
/* Accent: board green. Buttons use the darker value so white text passes AA. */
|
||||
--accent: #4F8160;
|
||||
--accent-hover: #6BA17D;
|
||||
--accent-soft: rgba(94, 139, 106, 0.16);
|
||||
--link: #8FC3A0;
|
||||
--link-hover: #B9E0C6;
|
||||
|
||||
/* Results */
|
||||
--ok: #6EDB9A;
|
||||
--warn: #E8B84A;
|
||||
--bad: #EF7B72;
|
||||
--orange: #E8955A;
|
||||
--purple: #B79FE0;
|
||||
--purple-soft: rgba(183, 159, 224, 0.14);
|
||||
|
||||
--font-sans: "Instrument Sans", system-ui, -apple-system, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif;
|
||||
|
||||
--radius: 3px;
|
||||
--shadow-card: none;
|
||||
}
|
||||
|
||||
::selection {
|
||||
background: rgba(94, 139, 106, 0.4);
|
||||
}
|
||||
|
||||
/* ---------- Chrome ---------- */
|
||||
|
||||
#topbar {
|
||||
background: rgba(20, 22, 26, 0.92);
|
||||
}
|
||||
|
||||
#topbar .brand-name {
|
||||
font-weight: 650;
|
||||
}
|
||||
|
||||
.page-title {
|
||||
font-size: 26px;
|
||||
font-weight: 600;
|
||||
letter-spacing: -0.015em;
|
||||
}
|
||||
|
||||
/* ---------- Labels: sentence case instead of tracked capitals ---------- */
|
||||
|
||||
#sidebar .nav-title,
|
||||
.card-title,
|
||||
.badge,
|
||||
.flag,
|
||||
#content .table-header th,
|
||||
#content .table-small-header th,
|
||||
.stat-label,
|
||||
.ev-meta dt,
|
||||
.ev-facts dt,
|
||||
.ev-player small,
|
||||
.ev-sel-stats span {
|
||||
text-transform: none;
|
||||
letter-spacing: 0;
|
||||
}
|
||||
|
||||
#sidebar .nav-title {
|
||||
font-size: 12.5px;
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
.card-title {
|
||||
color: var(--color-font2);
|
||||
font-size: 14px;
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
#content .table-header th,
|
||||
#content .table-small-header th {
|
||||
font-size: 12.5px;
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
/* The header's accent stripe carried no information */
|
||||
#content .table-header th:first-child {
|
||||
border-left: 0;
|
||||
}
|
||||
|
||||
.stat-label,
|
||||
.ev-meta dt,
|
||||
.ev-facts dt,
|
||||
.ev-player small {
|
||||
font-size: 12.5px;
|
||||
}
|
||||
|
||||
.flag {
|
||||
font-size: 11px;
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
.badge {
|
||||
font-size: 12px;
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
/* ---------- Surfaces: borders instead of shadows ---------- */
|
||||
|
||||
.card,
|
||||
.stat-card {
|
||||
box-shadow: none;
|
||||
}
|
||||
|
||||
/* Fleet and queue counters: number first, icon as a quiet marker */
|
||||
.stat-card {
|
||||
flex-direction: row-reverse;
|
||||
justify-content: space-between;
|
||||
align-items: flex-start;
|
||||
}
|
||||
|
||||
.stat-icon {
|
||||
width: auto;
|
||||
height: auto;
|
||||
background: none !important;
|
||||
font-size: 14px;
|
||||
}
|
||||
|
||||
.stat-value {
|
||||
font-size: 26px;
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
/* ---------- Colour tokens that were hardcoded in older files ---------- */
|
||||
|
||||
.badge-info {
|
||||
border-color: rgba(94, 139, 106, 0.45);
|
||||
color: #A9D4B7;
|
||||
}
|
||||
|
||||
#content a.seg-btn.active {
|
||||
box-shadow: inset 0 0 0 1px rgba(94, 139, 106, 0.5);
|
||||
}
|
||||
|
||||
.ev-move.is-active {
|
||||
border-color: rgba(94, 139, 106, 0.5);
|
||||
}
|
||||
|
||||
.ev-white .ev-piece { background-color: #EDEAE3; }
|
||||
.ev-black .ev-piece { background-color: #14161A; }
|
||||
|
||||
/* ==========================================================================
|
||||
LLR gauge (running SPRT tests)
|
||||
|
||||
The track runs from the lower bound (left) to the upper bound (right).
|
||||
The tall tick marks LLR = 0; the fill grows from it towards the current
|
||||
LLR, so direction and distance to a decision read at a glance.
|
||||
========================================================================== */
|
||||
|
||||
.llr {
|
||||
position: relative;
|
||||
min-width: 150px;
|
||||
height: 6px;
|
||||
margin-top: 10px;
|
||||
background-color: var(--line);
|
||||
border-radius: 1px;
|
||||
}
|
||||
|
||||
/* Bound markers at both ends */
|
||||
.llr::before,
|
||||
.llr::after {
|
||||
content: '';
|
||||
position: absolute;
|
||||
top: -3px;
|
||||
bottom: -3px;
|
||||
width: 2px;
|
||||
background-color: var(--line-strong);
|
||||
}
|
||||
|
||||
.llr::before { left: 0; }
|
||||
.llr::after { right: 0; }
|
||||
|
||||
.llr-fill {
|
||||
position: absolute;
|
||||
top: 0;
|
||||
bottom: 0;
|
||||
background-color: var(--muted);
|
||||
}
|
||||
|
||||
.llr-pos .llr-fill { background-color: var(--ok); }
|
||||
.llr-neg .llr-fill { background-color: var(--bad); }
|
||||
|
||||
.llr-zero {
|
||||
position: absolute;
|
||||
top: -4px;
|
||||
bottom: -4px;
|
||||
width: 1px;
|
||||
background-color: var(--color-font2);
|
||||
}
|
||||
|
||||
.llr-scale {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
margin-top: 5px;
|
||||
color: var(--muted);
|
||||
font-family: var(--font-mono);
|
||||
font-size: 10.5px;
|
||||
font-variant-numeric: tabular-nums;
|
||||
line-height: 1;
|
||||
}
|
||||
|
||||
.llr-scale b {
|
||||
color: var(--color-font1);
|
||||
font-weight: 500;
|
||||
}
|
||||
|
||||
/* ==========================================================================
|
||||
Result cells
|
||||
|
||||
A filled cell is a verdict: green passed, blue passed as a non-regression
|
||||
test, amber and red failed. A cell without a fill has no verdict yet, so it
|
||||
is only outlined, in warm grey that cannot be mistaken for the blue.
|
||||
A stopped test keeps the outline and gains diagonal hatching, like an entry
|
||||
that has been struck out.
|
||||
========================================================================== */
|
||||
|
||||
:root {
|
||||
--hatch: rgba(237, 234, 227, 0.14);
|
||||
}
|
||||
|
||||
/* Blue: a stronger fill, so it holds its own beside the green */
|
||||
#content .statblock-blue {
|
||||
background-color: rgba(76, 141, 255, 0.2);
|
||||
color: #A9CBFF;
|
||||
}
|
||||
|
||||
/* No verdict yet: running, pending, awaiting artifacts, stopped.
|
||||
.statblock- is the empty colour name the template renders for them, which
|
||||
also covers result cells that carry no state class. */
|
||||
#content .statblock.statblock-,
|
||||
#content .statblock.state-running,
|
||||
#content .statblock.state-pending,
|
||||
#content .statblock.state-awaiting,
|
||||
#content .statblock.state-stopped {
|
||||
background-color: transparent;
|
||||
box-shadow: inset 0 0 0 1px var(--line-strong);
|
||||
color: var(--color-font2);
|
||||
}
|
||||
|
||||
/* Nothing has been played yet */
|
||||
#content .statblock.state-pending,
|
||||
#content .statblock.state-awaiting {
|
||||
color: var(--muted);
|
||||
}
|
||||
|
||||
#content .statblock.state-stopped {
|
||||
background-image: repeating-linear-gradient(135deg, transparent 0, transparent 6px, var(--hatch) 6px, var(--hatch) 7.5px, transparent 7.5px, transparent 9px);
|
||||
}
|
||||
|
||||
/* Author names are shown in full; very long ones are clipped with an ellipsis */
|
||||
#content td.col-author {
|
||||
max-width: 14ch;
|
||||
}
|
||||
|
||||
#content td.col-author a {
|
||||
display: block;
|
||||
overflow: hidden;
|
||||
white-space: nowrap;
|
||||
text-overflow: ellipsis;
|
||||
}
|
||||
@@ -0,0 +1,286 @@
|
||||
/* Tune page: layout, collapsible sections, and the parameter history chart. */
|
||||
|
||||
/* ---------- Layout: a main column, and a side column ---------- */
|
||||
|
||||
#content .workload-container.tune-page {
|
||||
display: grid;
|
||||
grid-template-columns: minmax(0, 1fr) 320px;
|
||||
gap: 20px;
|
||||
align-items: start;
|
||||
}
|
||||
|
||||
#content .tune-page > .tune-main {
|
||||
grid-column: 1;
|
||||
grid-row: 1;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 20px;
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
#content .tune-page > .tune-side {
|
||||
grid-column: 2;
|
||||
grid-row: 1;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 16px;
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
#content .tune-main > .card,
|
||||
#content .tune-side > .card {
|
||||
margin: 0;
|
||||
}
|
||||
|
||||
/* Source order is side first; this puts the story in the right order */
|
||||
#content .tune-main > #spsa-panel { order: 1; }
|
||||
#content .tune-main > #results { order: 2; }
|
||||
#content .tune-main > #parameters { order: 3; }
|
||||
|
||||
@media (max-width: 1000px) {
|
||||
#content .workload-container.tune-page { grid-template-columns: minmax(0, 1fr); }
|
||||
#content .tune-page > .tune-main { grid-column: 1; grid-row: 1; }
|
||||
#content .tune-page > .tune-side { grid-column: 1; grid-row: 2; }
|
||||
}
|
||||
|
||||
/* ---------- Spacing inside the cards ---------- */
|
||||
|
||||
/* .card has no padding of its own: only its header is padded, so whatever
|
||||
follows has to keep clear of the border by itself. */
|
||||
#content .spsa-panel { padding-bottom: 16px; }
|
||||
|
||||
#content .spsa-panel > :not(.card-head) {
|
||||
margin-left: 16px;
|
||||
margin-right: 16px;
|
||||
}
|
||||
|
||||
#content .spsa-panel > .card-head + * { margin-top: 14px; }
|
||||
|
||||
/* The Modify button ends the Actions card and used to sit 4px from its edge */
|
||||
#content .workload-container #actions { padding-bottom: 16px; }
|
||||
#content .workload-container #actions .llr-history-panel { margin-bottom: 0; }
|
||||
|
||||
/* ---------- The parameter list scrolls inside the panel ---------- */
|
||||
|
||||
/* With dozens of parameters the list ran the page down to the results table.
|
||||
It now keeps to a bounded height; the filter and sort bar above it stays in
|
||||
view. The left padding keeps focus rings from being clipped. */
|
||||
#content .spsa-panel .spsa-rows {
|
||||
max-height: min(60vh, 540px);
|
||||
overflow-y: auto;
|
||||
overscroll-behavior: contain;
|
||||
scrollbar-width: thin;
|
||||
margin-left: 12px;
|
||||
padding-left: 4px;
|
||||
padding-right: 8px;
|
||||
}
|
||||
|
||||
/* ---------- Collapsible sections ---------- */
|
||||
|
||||
#content details.config-fold {
|
||||
padding: 0;
|
||||
}
|
||||
|
||||
.config-fold > summary {
|
||||
display: flex;
|
||||
align-items: baseline;
|
||||
gap: 12px;
|
||||
padding: 14px 18px;
|
||||
cursor: pointer;
|
||||
list-style: none;
|
||||
border-radius: inherit;
|
||||
}
|
||||
|
||||
.config-fold > summary::-webkit-details-marker { display: none; }
|
||||
|
||||
.config-fold > summary .card-title { margin: 0; }
|
||||
|
||||
.config-fold > summary:focus-visible {
|
||||
outline: 2px solid var(--accent, #4c8dff);
|
||||
outline-offset: -2px;
|
||||
}
|
||||
|
||||
.config-hint {
|
||||
flex: 1 1 auto;
|
||||
min-width: 0;
|
||||
font-size: 12.5px;
|
||||
color: var(--muted, var(--color-font3, #8b95a7));
|
||||
}
|
||||
|
||||
.config-fold > summary::after {
|
||||
content: '';
|
||||
flex: none;
|
||||
align-self: center;
|
||||
width: 7px;
|
||||
height: 7px;
|
||||
border-right: 1.5px solid currentColor;
|
||||
border-bottom: 1.5px solid currentColor;
|
||||
opacity: .6;
|
||||
transform: rotate(45deg) translateY(-2px);
|
||||
transition: transform .15s ease;
|
||||
}
|
||||
|
||||
.config-fold[open] > summary::after {
|
||||
transform: rotate(-135deg) translateY(-2px);
|
||||
}
|
||||
|
||||
.config-fold[open] > summary {
|
||||
border-bottom: 1px solid var(--line, #2a303a);
|
||||
}
|
||||
|
||||
.config-fold > :not(summary) {
|
||||
padding-left: 18px;
|
||||
padding-right: 18px;
|
||||
}
|
||||
|
||||
.config-fold > table { margin-top: 8px; margin-bottom: 12px; width: calc(100% - 36px); }
|
||||
|
||||
/* ---------- Parameter names double as "show on chart" buttons ---------- */
|
||||
|
||||
button.spsa-name {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
text-align: left;
|
||||
cursor: pointer;
|
||||
color: var(--spsa-ink);
|
||||
background: none;
|
||||
border: 0;
|
||||
font-family: var(--spsa-mono);
|
||||
font-size: 13.5px;
|
||||
}
|
||||
|
||||
button.spsa-name::before {
|
||||
content: '';
|
||||
flex: none;
|
||||
width: 8px;
|
||||
height: 8px;
|
||||
border-radius: 50%;
|
||||
background: var(--row-color, transparent);
|
||||
opacity: 0;
|
||||
}
|
||||
|
||||
.spsa-row.is-shown button.spsa-name::before { opacity: 1; }
|
||||
.spsa-row.is-pinned button.spsa-name { text-decoration: underline; text-underline-offset: 3px; }
|
||||
|
||||
button.spsa-name:focus-visible {
|
||||
outline: 2px solid var(--spsa-fill);
|
||||
outline-offset: 3px;
|
||||
border-radius: 2px;
|
||||
}
|
||||
|
||||
/* ---------- History chart ---------- */
|
||||
|
||||
.spsa-history {
|
||||
padding: 4px 0 18px;
|
||||
}
|
||||
|
||||
.spsa-history-head h3 {
|
||||
margin: 0;
|
||||
font-size: 14px;
|
||||
font-weight: 600;
|
||||
color: var(--spsa-ink);
|
||||
}
|
||||
|
||||
.spsa-history-head p {
|
||||
margin: 2px 0 10px;
|
||||
font-size: 13px;
|
||||
color: var(--spsa-muted);
|
||||
}
|
||||
|
||||
.spsa-chart { position: relative; width: 100%; }
|
||||
|
||||
.sch-plot {
|
||||
position: relative;
|
||||
cursor: crosshair;
|
||||
touch-action: pan-y;
|
||||
user-select: none;
|
||||
-webkit-user-select: none;
|
||||
}
|
||||
|
||||
.sch-plot:focus-visible {
|
||||
outline: 2px solid var(--spsa-fill);
|
||||
outline-offset: 4px;
|
||||
}
|
||||
|
||||
.sch-svg { display: block; width: 100%; height: auto; overflow: visible; }
|
||||
|
||||
.sch-bg { fill: transparent; }
|
||||
|
||||
.sch-grid { stroke: rgba(197, 204, 217, .09); stroke-width: 1; shape-rendering: crispEdges; }
|
||||
.sch-zero { stroke: var(--spsa-muted); stroke-width: 1; opacity: .65; shape-rendering: crispEdges; }
|
||||
|
||||
.sch-tick {
|
||||
fill: var(--spsa-muted);
|
||||
font: 500 10px var(--spsa-mono);
|
||||
}
|
||||
|
||||
.sch-line {
|
||||
fill: none;
|
||||
stroke-linecap: round;
|
||||
stroke-linejoin: round;
|
||||
}
|
||||
|
||||
.sch-line.is-quiet { stroke: var(--spsa-muted); stroke-width: 1; opacity: .24; }
|
||||
.sch-line.is-on { stroke-width: 2; }
|
||||
|
||||
.sch-label { font: 600 11px var(--spsa-mono); }
|
||||
|
||||
.sch-hover-line {
|
||||
stroke: var(--spsa-ink);
|
||||
stroke-width: 1;
|
||||
stroke-dasharray: 2 2;
|
||||
opacity: 0;
|
||||
}
|
||||
|
||||
.sch-hover-line.is-active { opacity: .7; }
|
||||
|
||||
.sch-dot { stroke: var(--color2, #1a1d22); stroke-width: 1.5; }
|
||||
|
||||
.c0 { stroke: #5fa0ff; fill: #5fa0ff; }
|
||||
.c1 { stroke: #6ee7b7; fill: #6ee7b7; }
|
||||
.c2 { stroke: #f2c94c; fill: #f2c94c; }
|
||||
.c3 { stroke: #c4a1ff; fill: #c4a1ff; }
|
||||
.c4 { stroke: #ff8f84; fill: #ff8f84; }
|
||||
|
||||
.sch-line.c0, .sch-line.c1, .sch-line.c2, .sch-line.c3, .sch-line.c4 { fill: none; }
|
||||
.sch-label.c0, .sch-label.c1, .sch-label.c2, .sch-label.c3, .sch-label.c4 { stroke: none; }
|
||||
|
||||
.sch-tip {
|
||||
position: absolute;
|
||||
left: 0;
|
||||
top: 0;
|
||||
z-index: 1;
|
||||
min-width: 150px;
|
||||
padding: 8px 10px;
|
||||
background: rgba(14, 16, 20, .96);
|
||||
border: 1px solid var(--line-strong, #3a3f48);
|
||||
border-radius: 4px;
|
||||
color: var(--spsa-ink);
|
||||
font: 500 12px var(--spsa-mono);
|
||||
white-space: nowrap;
|
||||
pointer-events: none;
|
||||
opacity: 0;
|
||||
transition: opacity .12s ease;
|
||||
}
|
||||
|
||||
.sch-tip.is-active { opacity: 1; }
|
||||
|
||||
.sch-tip .t-games { margin-bottom: 4px; color: var(--spsa-muted); }
|
||||
|
||||
.sch-tip .t-row { display: flex; align-items: center; gap: 8px; line-height: 1.6; }
|
||||
.sch-tip .t-swatch { flex: none; width: 8px; height: 8px; border-radius: 50%; }
|
||||
.sch-tip .t-name { margin-right: auto; padding-right: 12px; }
|
||||
.sch-tip .t-delta { color: var(--spsa-muted); }
|
||||
|
||||
.spsa-note {
|
||||
margin: 8px 0 0;
|
||||
font-size: 12.5px;
|
||||
color: var(--spsa-muted);
|
||||
}
|
||||
|
||||
@media (prefers-reduced-motion: reduce) {
|
||||
.sch-tip, .config-fold > summary::after { transition: none; }
|
||||
}
|
||||
@@ -0,0 +1,511 @@
|
||||
/* SPSA history chart (Tune pages).
|
||||
|
||||
The server (mytags.spsa_history_chart) supplies every parameter's value over
|
||||
time as <div class="spsa-chart" data-chart="{json}">. Each line is one
|
||||
parameter, drawn as how far it has travelled from its start value, as a share
|
||||
of its allowed range, so parameters with very different scales share an axis.
|
||||
|
||||
A few lines are highlighted at a time. By default that is the three that moved
|
||||
the most. Hovering a parameter's name in the list follows that one, and
|
||||
clicking a name pins it, so several can be compared. */
|
||||
|
||||
(function () {
|
||||
'use strict';
|
||||
|
||||
var SVG_NS = 'http://www.w3.org/2000/svg';
|
||||
var MINUS = '−';
|
||||
var HEIGHT = 230;
|
||||
var MARGIN = { l: 46, r: 100, t: 12, b: 22 };
|
||||
var COLOURS = 5;
|
||||
var MAX_ON = 8;
|
||||
|
||||
function svg(name, attrs, parent) {
|
||||
var node = document.createElementNS(SVG_NS, name);
|
||||
for (var key in attrs)
|
||||
if (Object.prototype.hasOwnProperty.call(attrs, key))
|
||||
node.setAttribute(key, attrs[key]);
|
||||
if (parent)
|
||||
parent.appendChild(node);
|
||||
return node;
|
||||
}
|
||||
|
||||
function html(name, className, parent) {
|
||||
var node = document.createElement(name);
|
||||
if (className)
|
||||
node.className = className;
|
||||
if (parent)
|
||||
parent.appendChild(node);
|
||||
return node;
|
||||
}
|
||||
|
||||
function clamp(value, lo, hi) {
|
||||
return Math.max(lo, Math.min(hi, value));
|
||||
}
|
||||
|
||||
function percent(value) {
|
||||
var shown = Math.abs(value) < 10 ? Math.abs(value).toFixed(1) : String(Math.round(Math.abs(value)));
|
||||
return (value > 0 ? '+' : value < 0 ? MINUS : '') + shown + '%';
|
||||
}
|
||||
|
||||
function amount(value, integer) {
|
||||
return integer ? String(Math.round(value)) : value.toFixed(4);
|
||||
}
|
||||
|
||||
function commas(value) {
|
||||
return String(Math.round(value)).replace(/\B(?=(\d{3})+(?!\d))/g, ',');
|
||||
}
|
||||
|
||||
function short(name) {
|
||||
return name.length > 13 ? name.slice(0, 12) + '…' : name;
|
||||
}
|
||||
|
||||
/* ---------- Chart ---------- */
|
||||
|
||||
function Chart(root, data, rows) {
|
||||
|
||||
var self = this;
|
||||
|
||||
this.root = root;
|
||||
this.data = data;
|
||||
this.rows = rows; // list items, by parameter index
|
||||
this.pinned = [];
|
||||
this.hover = -1;
|
||||
this.active = -1;
|
||||
this.width = 0;
|
||||
|
||||
this.load(data);
|
||||
|
||||
root.textContent = '';
|
||||
|
||||
this.plot = html('div', 'sch-plot', root);
|
||||
this.plot.tabIndex = 0;
|
||||
this.plot.setAttribute('role', 'img');
|
||||
this.plot.setAttribute('aria-label', 'Parameter history. Use the arrow keys to inspect the points.');
|
||||
|
||||
this.svg = svg('svg', { 'class': 'sch-svg', 'aria-hidden': 'true' }, this.plot);
|
||||
this.tip = html('div', 'sch-tip', this.plot);
|
||||
|
||||
this.render();
|
||||
this.bind();
|
||||
}
|
||||
|
||||
// What is drawn follows from the server's data. Live updates call this again with newer data.
|
||||
Chart.prototype.load = function (data) {
|
||||
|
||||
this.data = data;
|
||||
|
||||
// Movement from the start value, as a share of the allowed range
|
||||
this.series = data.names.map(function (name, i) {
|
||||
var span = (data.max[i] - data.min[i]) || 1;
|
||||
return data.points.map(function (point) {
|
||||
return (point[1 + i] - data.start[i]) / span * 100;
|
||||
});
|
||||
});
|
||||
|
||||
// Without a choice, follow whichever parameters moved the most
|
||||
var last = this.series.map(function (line, i) {
|
||||
return { index: i, size: Math.abs(line[line.length - 1]) };
|
||||
});
|
||||
last.sort(function (a, b) { return b.size - a.size || a.index - b.index; });
|
||||
this.defaults = last.slice(0, 3).map(function (entry) { return entry.index; });
|
||||
};
|
||||
|
||||
// Newer data, same chart: pinned lines and the point being inspected stay as they are
|
||||
Chart.prototype.update = function (data) {
|
||||
this.load(data);
|
||||
this.render();
|
||||
};
|
||||
|
||||
Chart.prototype.shown = function () {
|
||||
|
||||
var list = this.pinned.slice();
|
||||
|
||||
if (this.hover >= 0 && list.indexOf(this.hover) < 0)
|
||||
list.push(this.hover);
|
||||
|
||||
if (!list.length)
|
||||
list = this.defaults.slice();
|
||||
|
||||
return list.slice(0, MAX_ON);
|
||||
};
|
||||
|
||||
Chart.prototype.render = function () {
|
||||
|
||||
var W = Math.floor(this.plot.clientWidth);
|
||||
if (W < 160)
|
||||
return;
|
||||
|
||||
this.width = W;
|
||||
|
||||
var H = HEIGHT, m = MARGIN;
|
||||
var iw = W - m.l - m.r, ih = H - m.t - m.b;
|
||||
var points = this.data.points;
|
||||
var xMax = Math.max(points[points.length - 1][0], 1);
|
||||
var shown = this.shown();
|
||||
var series = this.series;
|
||||
|
||||
// Vertical range: everything that moved, and zero
|
||||
var lo = 0, hi = 0;
|
||||
series.forEach(function (line) {
|
||||
line.forEach(function (v) {
|
||||
if (v < lo) lo = v;
|
||||
if (v > hi) hi = v;
|
||||
});
|
||||
});
|
||||
|
||||
var pad = Math.max((hi - lo) * 0.12, 1);
|
||||
lo -= pad; hi += pad;
|
||||
|
||||
function sx(games) { return m.l + iw * (games / xMax); }
|
||||
function sy(value) { return m.t + ih * (1 - (value - lo) / (hi - lo)); }
|
||||
|
||||
this.geo = { W: W, H: H, iw: iw, ih: ih, xMax: xMax, sx: sx, sy: sy };
|
||||
|
||||
var el = this.svg;
|
||||
el.textContent = '';
|
||||
el.setAttribute('viewBox', '0 0 ' + W + ' ' + H);
|
||||
el.setAttribute('width', W);
|
||||
el.setAttribute('height', H);
|
||||
|
||||
svg('rect', { 'class': 'sch-bg', x: m.l, y: m.t, width: iw, height: ih }, el);
|
||||
|
||||
// Horizontal grid, with the zero line emphasised
|
||||
[hi, (hi + lo) / 2, lo].forEach(function (value) {
|
||||
var y = sy(value);
|
||||
svg('line', { 'class': 'sch-grid', x1: m.l, x2: m.l + iw, y1: y, y2: y }, el);
|
||||
svg('text', { 'class': 'sch-tick', x: m.l - 8, y: y, dy: '0.32em', 'text-anchor': 'end' }, el).textContent = percent(value);
|
||||
});
|
||||
|
||||
svg('line', { 'class': 'sch-zero', x1: m.l, x2: m.l + iw, y1: sy(0), y2: sy(0) }, el);
|
||||
svg('text', { 'class': 'sch-tick', x: m.l - 8, y: sy(0), dy: '0.32em', 'text-anchor': 'end' }, el).textContent = '0';
|
||||
|
||||
// Games axis
|
||||
[[0, 'start', m.l], [xMax / 2, 'middle', m.l + iw / 2], [xMax, 'end', m.l + iw]].forEach(function (tick) {
|
||||
var label = svg('text', { 'class': 'sch-tick', x: tick[2], y: H - 5, 'text-anchor': tick[1] }, el);
|
||||
label.textContent = tick[0] === 0 ? '0 games' : commas(tick[0]);
|
||||
});
|
||||
|
||||
// Lines: the quiet ones first, so the highlighted ones sit on top
|
||||
function path(line) {
|
||||
return line.map(function (v, k) {
|
||||
return (k ? 'L' : 'M') + sx(points[k][0]).toFixed(1) + ' ' + sy(v).toFixed(1);
|
||||
}).join('');
|
||||
}
|
||||
|
||||
series.forEach(function (line, i) {
|
||||
if (shown.indexOf(i) < 0)
|
||||
svg('path', { 'class': 'sch-line is-quiet', d: path(line) }, el);
|
||||
});
|
||||
|
||||
shown.forEach(function (i, order) {
|
||||
svg('path', { 'class': 'sch-line is-on c' + (order % COLOURS), d: path(series[i]) }, el);
|
||||
});
|
||||
|
||||
// Names at the end of each highlighted line, kept apart from one another
|
||||
var labels = shown.map(function (i, order) {
|
||||
var line = series[i];
|
||||
return { index: i, order: order, y: sy(line[line.length - 1]) };
|
||||
}).sort(function (a, b) { return a.y - b.y; });
|
||||
|
||||
for (var k = 1; k < labels.length; k++)
|
||||
if (labels[k].y - labels[k - 1].y < 13)
|
||||
labels[k].y = labels[k - 1].y + 13;
|
||||
|
||||
labels.forEach(function (label) {
|
||||
var line = series[label.index];
|
||||
svg('circle', { 'class': 'sch-dot c' + (label.order % COLOURS), cx: sx(points[points.length - 1][0]), cy: sy(line[line.length - 1]), r: 3.5 }, el);
|
||||
svg('text', { 'class': 'sch-label c' + (label.order % COLOURS), x: m.l + iw + 10, y: label.y, dy: '0.32em' }, el).textContent = short(this.data.names[label.index]);
|
||||
}, this);
|
||||
|
||||
// Marker
|
||||
this.hoverLine = svg('line', { 'class': 'sch-hover-line', y1: m.t, y2: m.t + ih }, el);
|
||||
this.hoverDots = shown.map(function (i, order) {
|
||||
return svg('circle', { 'class': 'sch-dot c' + (order % COLOURS), r: 3.5, opacity: 0 }, el);
|
||||
});
|
||||
|
||||
this.syncRows(shown);
|
||||
|
||||
if (this.active >= 0)
|
||||
this.setActive(this.active);
|
||||
};
|
||||
|
||||
/* ---------- Rows in the parameter list ---------- */
|
||||
|
||||
Chart.prototype.syncRows = function (shown) {
|
||||
|
||||
var self = this;
|
||||
|
||||
this.rows.forEach(function (row, i) {
|
||||
|
||||
if (!row)
|
||||
return;
|
||||
|
||||
var order = shown.indexOf(i);
|
||||
var on = order >= 0 && (self.pinned.length || self.hover >= 0 || false);
|
||||
|
||||
row.classList.toggle('is-shown', on);
|
||||
row.classList.toggle('is-pinned', self.pinned.indexOf(i) >= 0);
|
||||
|
||||
if (on)
|
||||
row.style.setProperty('--row-color', ['#5fa0ff', '#6ee7b7', '#f2c94c', '#c4a1ff', '#ff8f84'][order % COLOURS]);
|
||||
else
|
||||
row.style.removeProperty('--row-color');
|
||||
});
|
||||
};
|
||||
|
||||
/* ---------- Inspecting a point ---------- */
|
||||
|
||||
Chart.prototype.nearest = function (x) {
|
||||
|
||||
var g = this.geo, points = this.data.points;
|
||||
var target = clamp((x - MARGIN.l) / g.iw, 0, 1) * g.xMax;
|
||||
var best = 0, distance = Infinity;
|
||||
|
||||
for (var k = 0; k < points.length; k++) {
|
||||
var d = Math.abs(points[k][0] - target);
|
||||
if (d < distance) { distance = d; best = k; }
|
||||
}
|
||||
|
||||
return best;
|
||||
};
|
||||
|
||||
Chart.prototype.setActive = function (index) {
|
||||
|
||||
if (!this.geo)
|
||||
return;
|
||||
|
||||
var g = this.geo, points = this.data.points, data = this.data;
|
||||
|
||||
if (index < 0) {
|
||||
this.active = -1;
|
||||
this.hoverLine.classList.remove('is-active');
|
||||
this.hoverDots.forEach(function (dot) { dot.setAttribute('opacity', 0); });
|
||||
this.tip.classList.remove('is-active');
|
||||
return;
|
||||
}
|
||||
|
||||
this.active = index = clamp(index, 0, points.length - 1);
|
||||
|
||||
var shown = this.shown();
|
||||
var x = g.sx(points[index][0]);
|
||||
|
||||
this.hoverLine.setAttribute('x1', x);
|
||||
this.hoverLine.setAttribute('x2', x);
|
||||
this.hoverLine.classList.add('is-active');
|
||||
|
||||
this.hoverDots.forEach(function (dot, order) {
|
||||
dot.setAttribute('cx', x);
|
||||
dot.setAttribute('cy', g.sy(this.series[shown[order]][index]));
|
||||
dot.setAttribute('opacity', 1);
|
||||
}, this);
|
||||
|
||||
// Tooltip: the games played, then each highlighted parameter's value there
|
||||
var tip = this.tip;
|
||||
tip.textContent = '';
|
||||
html('div', 't-games', tip).textContent = commas(points[index][0]) + ' games';
|
||||
|
||||
shown.forEach(function (i, order) {
|
||||
var row = html('div', 't-row', tip);
|
||||
var swatch = html('span', 't-swatch c' + (order % COLOURS), row);
|
||||
swatch.style.background = ['#5fa0ff', '#6ee7b7', '#f2c94c', '#c4a1ff', '#ff8f84'][order % COLOURS];
|
||||
html('span', 't-name', row).textContent = data.names[i];
|
||||
html('span', 't-value', row).textContent = amount(points[index][1 + i], data.integer[i]);
|
||||
html('span', 't-delta', row).textContent = percent(this.series[i][index]);
|
||||
}, this);
|
||||
|
||||
tip.classList.add('is-active');
|
||||
|
||||
var left = clamp(x + 12, 0, g.W - tip.offsetWidth);
|
||||
if (x + 12 + tip.offsetWidth > g.W - 4)
|
||||
left = clamp(x - tip.offsetWidth - 12, 0, g.W - tip.offsetWidth);
|
||||
|
||||
tip.style.left = left + 'px';
|
||||
tip.style.top = MARGIN.t + 'px';
|
||||
};
|
||||
|
||||
/* ---------- Events ---------- */
|
||||
|
||||
Chart.prototype.redraw = function () {
|
||||
this.render();
|
||||
};
|
||||
|
||||
Chart.prototype.togglePin = function (index) {
|
||||
|
||||
var at = this.pinned.indexOf(index);
|
||||
if (at >= 0)
|
||||
this.pinned.splice(at, 1);
|
||||
else if (this.pinned.length < MAX_ON)
|
||||
this.pinned.push(index);
|
||||
|
||||
this.redraw();
|
||||
};
|
||||
|
||||
Chart.prototype.follow = function (index) {
|
||||
this.hover = index;
|
||||
this.redraw();
|
||||
};
|
||||
|
||||
Chart.prototype.bind = function () {
|
||||
|
||||
var self = this, plot = this.plot;
|
||||
|
||||
function move(event) {
|
||||
if (!self.geo)
|
||||
return;
|
||||
var box = self.svg.getBoundingClientRect();
|
||||
var x = (event.clientX - box.left) * (self.geo.W / (box.width || self.geo.W));
|
||||
self.setActive(self.nearest(x));
|
||||
}
|
||||
|
||||
plot.addEventListener('pointerenter', move);
|
||||
plot.addEventListener('pointermove', move);
|
||||
plot.addEventListener('pointerdown', move);
|
||||
plot.addEventListener('pointerleave', function (event) {
|
||||
if (event.pointerType === 'mouse')
|
||||
self.setActive(-1);
|
||||
});
|
||||
|
||||
plot.addEventListener('keydown', function (event) {
|
||||
|
||||
var last = self.data.points.length - 1;
|
||||
var step = event.shiftKey ? 10 : 1;
|
||||
var index = self.active;
|
||||
|
||||
if (event.key === 'ArrowLeft') index = index < 0 ? last : index - step;
|
||||
else if (event.key === 'ArrowRight') index = index < 0 ? last : index + step;
|
||||
else if (event.key === 'Home') index = 0;
|
||||
else if (event.key === 'End') index = last;
|
||||
else if (event.key === 'Escape') { self.setActive(-1); return; }
|
||||
else return;
|
||||
|
||||
event.preventDefault();
|
||||
self.setActive(clamp(index, 0, last));
|
||||
});
|
||||
|
||||
plot.addEventListener('blur', function () { self.setActive(-1); });
|
||||
|
||||
// Names in the list
|
||||
this.rows.forEach(function (row, i) {
|
||||
|
||||
if (!row)
|
||||
return;
|
||||
|
||||
var button = row.querySelector('.spsa-name');
|
||||
if (!button)
|
||||
return;
|
||||
|
||||
row.addEventListener('mouseenter', function () { self.follow(i); });
|
||||
row.addEventListener('mouseleave', function () { self.follow(-1); });
|
||||
button.addEventListener('focus', function () { self.follow(i); });
|
||||
button.addEventListener('blur', function () { self.follow(-1); });
|
||||
|
||||
button.addEventListener('click', function () {
|
||||
self.togglePin(i);
|
||||
button.setAttribute('aria-pressed', self.pinned.indexOf(i) >= 0 ? 'true' : 'false');
|
||||
});
|
||||
});
|
||||
|
||||
// Keep the chart as wide as its panel
|
||||
if ('ResizeObserver' in window) {
|
||||
var queued = false;
|
||||
new ResizeObserver(function () {
|
||||
if (queued) return;
|
||||
queued = true;
|
||||
window.requestAnimationFrame(function () {
|
||||
queued = false;
|
||||
if (Math.floor(plot.clientWidth) !== self.width)
|
||||
self.render();
|
||||
});
|
||||
}).observe(plot);
|
||||
} else {
|
||||
window.addEventListener('resize', function () {
|
||||
if (Math.floor(plot.clientWidth) !== self.width)
|
||||
self.render();
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
/* ---------- Start ---------- */
|
||||
|
||||
function note(root, text) {
|
||||
root.textContent = '';
|
||||
html('p', 'spsa-note', root).textContent = text;
|
||||
}
|
||||
|
||||
var chart = null; // the chart on the page, once there is something to draw
|
||||
|
||||
function mount(root, raw) {
|
||||
|
||||
var data;
|
||||
try {
|
||||
data = JSON.parse(raw);
|
||||
} catch (error) {
|
||||
chart = null;
|
||||
return note(root, 'The history could not be read.');
|
||||
}
|
||||
|
||||
// The notice about missing history sits beside the chart, and is redone with it
|
||||
var parent = root.parentNode;
|
||||
Array.prototype.slice.call(parent.children).forEach(function (child) {
|
||||
if (child !== root && child.classList.contains('spsa-note'))
|
||||
parent.removeChild(child);
|
||||
});
|
||||
|
||||
if (!data.names.length || data.points.length < 2 || !data.games) {
|
||||
chart = null;
|
||||
return note(root, 'No games have been played yet. The chart appears with the first results.');
|
||||
}
|
||||
|
||||
if (chart && chart.root === root && root.querySelector('.sch-plot')) {
|
||||
|
||||
// Live update: the same chart, with newer data
|
||||
chart.update(data);
|
||||
|
||||
} else {
|
||||
|
||||
var items = document.querySelectorAll('#spsa-rows .spsa-row');
|
||||
var rows = [];
|
||||
for (var k = 0; k < items.length; k++)
|
||||
rows[parseInt(items[k].getAttribute('data-index'), 10)] = items[k];
|
||||
|
||||
chart = new Chart(root, data, rows);
|
||||
}
|
||||
|
||||
if (!data.recorded) {
|
||||
var message = html('p', 'spsa-note');
|
||||
message.setAttribute('data-live-skip', '');
|
||||
message.textContent = 'History starts recording with the next result. Until then the chart shows only the start and the current values.';
|
||||
parent.appendChild(message);
|
||||
}
|
||||
}
|
||||
|
||||
function start() {
|
||||
|
||||
var root = document.querySelector('.spsa-chart[data-chart]');
|
||||
if (root)
|
||||
mount(root, root.getAttribute('data-chart'));
|
||||
}
|
||||
|
||||
/* Live updates ( live.js ) never touch the chart itself. When a fresh page
|
||||
arrives with more history, the data is handed over here instead. */
|
||||
document.addEventListener('live:patched', function (event) {
|
||||
|
||||
var root = document.querySelector('.spsa-chart[data-chart]');
|
||||
var next = event.detail && event.detail.fresh && event.detail.fresh.querySelector('.spsa-chart[data-chart]');
|
||||
if (!root || !next)
|
||||
return;
|
||||
|
||||
var raw = next.getAttribute('data-chart');
|
||||
if (raw === root.getAttribute('data-chart'))
|
||||
return;
|
||||
|
||||
root.setAttribute('data-chart', raw);
|
||||
mount(root, raw);
|
||||
});
|
||||
|
||||
if (document.readyState === 'loading')
|
||||
document.addEventListener('DOMContentLoaded', start);
|
||||
else
|
||||
start();
|
||||
|
||||
})();
|
||||
@@ -0,0 +1,225 @@
|
||||
/* SPSA parameter panel (Tune pages).
|
||||
|
||||
One row per parameter. The track is the parameter's allowed range, the hollow
|
||||
tick is where tuning started, the dot is where it is now, and the bar between
|
||||
them is how far it has travelled. A parameter pressed against its limit gets
|
||||
a warm dot, because that usually means the range is too tight. */
|
||||
|
||||
.spsa-panel {
|
||||
--spsa-line: var(--line, #2a303a);
|
||||
--spsa-muted: var(--muted, var(--color-font3, #8b95a7));
|
||||
--spsa-ink: var(--color-font1, #e6e9ef);
|
||||
--spsa-fill: var(--accent, #4c8dff);
|
||||
--spsa-limit: #e8955a;
|
||||
--spsa-mono: var(--font-mono, 'JetBrains Mono', ui-monospace, SFMono-Regular, Menlo, Consolas, monospace);
|
||||
}
|
||||
|
||||
/* ---------- Progress ---------- */
|
||||
|
||||
.spsa-summary {
|
||||
display: grid;
|
||||
grid-template-columns: auto 1fr auto;
|
||||
align-items: end;
|
||||
gap: 8px 28px;
|
||||
padding: 4px 0 18px;
|
||||
}
|
||||
|
||||
.spsa-iter { display: flex; flex-direction: column; gap: 2px; }
|
||||
|
||||
.spsa-big {
|
||||
font-family: var(--spsa-mono);
|
||||
font-size: 30px;
|
||||
font-weight: 600;
|
||||
line-height: 1;
|
||||
color: var(--spsa-ink);
|
||||
font-variant-numeric: tabular-nums;
|
||||
}
|
||||
|
||||
.spsa-of { font-size: 13px; color: var(--spsa-muted); }
|
||||
|
||||
.spsa-bar {
|
||||
height: 6px;
|
||||
margin-bottom: 7px;
|
||||
background: var(--spsa-line);
|
||||
border-radius: 3px;
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
.spsa-bar > span {
|
||||
display: block;
|
||||
height: 100%;
|
||||
background: var(--spsa-fill);
|
||||
border-radius: 3px;
|
||||
}
|
||||
|
||||
.spsa-facts { display: flex; gap: 22px; margin: 0; }
|
||||
.spsa-facts div { text-align: right; }
|
||||
.spsa-facts dt { font-size: 12.5px; color: var(--spsa-muted); }
|
||||
.spsa-facts dd {
|
||||
margin: 0;
|
||||
font-family: var(--spsa-mono);
|
||||
font-size: 15px;
|
||||
color: var(--spsa-ink);
|
||||
font-variant-numeric: tabular-nums;
|
||||
}
|
||||
|
||||
/* ---------- Tools ---------- */
|
||||
|
||||
.spsa-tools {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 10px;
|
||||
padding: 12px 0;
|
||||
border-top: 1px solid var(--spsa-line);
|
||||
}
|
||||
|
||||
.spsa-tools input[type=search],
|
||||
.spsa-tools select {
|
||||
min-height: 36px;
|
||||
padding: 0 10px;
|
||||
color: var(--spsa-ink);
|
||||
background: transparent;
|
||||
border: 1px solid var(--spsa-line);
|
||||
border-radius: 4px;
|
||||
font: inherit;
|
||||
font-size: 14px;
|
||||
}
|
||||
|
||||
.spsa-tools input[type=search] { flex: 1 1 200px; max-width: 320px; }
|
||||
|
||||
.spsa-tools :focus-visible,
|
||||
.spsa-row:focus-visible {
|
||||
outline: 2px solid var(--spsa-fill);
|
||||
outline-offset: 2px;
|
||||
}
|
||||
|
||||
/* ---------- Rows ---------- */
|
||||
|
||||
.spsa-rows { list-style: none; margin: 0; padding: 0; }
|
||||
|
||||
.spsa-row {
|
||||
display: grid;
|
||||
grid-template-columns: minmax(8ch, 18ch) minmax(140px, 1fr) 10ch 9ch;
|
||||
align-items: center;
|
||||
gap: 4px 18px;
|
||||
padding: 11px 0;
|
||||
border-top: 1px solid var(--spsa-line);
|
||||
}
|
||||
|
||||
.spsa-row[hidden] { display: none; }
|
||||
|
||||
.spsa-name {
|
||||
font-family: var(--spsa-mono);
|
||||
font-size: 13.5px;
|
||||
color: var(--spsa-ink);
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
|
||||
.spsa-track-wrap { min-width: 0; }
|
||||
|
||||
.spsa-track {
|
||||
position: relative;
|
||||
height: 4px;
|
||||
margin: 8px 6px 6px;
|
||||
background: var(--spsa-line);
|
||||
border-radius: 2px;
|
||||
}
|
||||
|
||||
.spsa-drift {
|
||||
position: absolute;
|
||||
top: 0;
|
||||
bottom: 0;
|
||||
background: var(--spsa-fill);
|
||||
opacity: .55;
|
||||
}
|
||||
|
||||
.spsa-start {
|
||||
position: absolute;
|
||||
top: -5px;
|
||||
width: 2px;
|
||||
height: 14px;
|
||||
margin-left: -1px;
|
||||
background: var(--spsa-muted);
|
||||
}
|
||||
|
||||
.spsa-now {
|
||||
position: absolute;
|
||||
top: 50%;
|
||||
width: 12px;
|
||||
height: 12px;
|
||||
margin: -6px 0 0 -6px;
|
||||
background: var(--spsa-fill);
|
||||
border: 2px solid var(--color2, #1a1d22);
|
||||
border-radius: 50%;
|
||||
box-sizing: border-box;
|
||||
}
|
||||
|
||||
.spsa-row.at-bound .spsa-now { background: var(--spsa-limit); }
|
||||
|
||||
.spsa-scale {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
font-family: var(--spsa-mono);
|
||||
font-size: 11px;
|
||||
color: var(--spsa-muted);
|
||||
font-variant-numeric: tabular-nums;
|
||||
}
|
||||
|
||||
.spsa-value {
|
||||
font-family: var(--spsa-mono);
|
||||
font-size: 15px;
|
||||
font-weight: 600;
|
||||
text-align: right;
|
||||
color: var(--spsa-ink);
|
||||
font-variant-numeric: tabular-nums;
|
||||
}
|
||||
|
||||
.spsa-delta {
|
||||
font-family: var(--spsa-mono);
|
||||
font-size: 13px;
|
||||
text-align: right;
|
||||
color: var(--spsa-muted);
|
||||
font-variant-numeric: tabular-nums;
|
||||
}
|
||||
|
||||
.spsa-row.at-bound .spsa-delta { color: var(--spsa-limit); }
|
||||
|
||||
.spsa-empty { padding: 18px 0; color: var(--spsa-muted); }
|
||||
|
||||
.spsa-key {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 6px 20px;
|
||||
padding-top: 12px;
|
||||
border-top: 1px solid var(--spsa-line);
|
||||
font-size: 12.5px;
|
||||
color: var(--spsa-muted);
|
||||
}
|
||||
|
||||
.spsa-key i {
|
||||
display: inline-block;
|
||||
vertical-align: middle;
|
||||
margin-right: 6px;
|
||||
}
|
||||
|
||||
.spsa-key .k-start { width: 2px; height: 12px; background: var(--spsa-muted); }
|
||||
.spsa-key .k-now { width: 10px; height: 10px; border-radius: 50%; background: var(--spsa-fill); }
|
||||
.spsa-key .k-limit { width: 10px; height: 10px; border-radius: 50%; background: var(--spsa-limit); }
|
||||
|
||||
/* ---------- Narrow screens ---------- */
|
||||
|
||||
@media (max-width: 720px) {
|
||||
|
||||
.spsa-summary { grid-template-columns: 1fr; }
|
||||
.spsa-facts div { text-align: left; }
|
||||
|
||||
.spsa-row {
|
||||
grid-template-columns: 1fr auto auto;
|
||||
gap: 6px 12px;
|
||||
}
|
||||
|
||||
.spsa-name { grid-column: 1; }
|
||||
.spsa-value { grid-column: 2; }
|
||||
.spsa-delta { grid-column: 3; min-width: 7ch; }
|
||||
.spsa-track-wrap { grid-column: 1 / -1; }
|
||||
}
|
||||
@@ -0,0 +1,110 @@
|
||||
/* SPSA parameter panel: filter by name, sort by how far a parameter moved.
|
||||
|
||||
Live updates ( live.js ) never replace the rows, so the order, the filter,
|
||||
the pinned lines and the hover all survive a refresh. The numbers in the
|
||||
rows are brought up to date here, from the page that was just fetched. */
|
||||
|
||||
(function () {
|
||||
|
||||
// The parts of a row that only show numbers ( nothing in them carries a listener )
|
||||
var CELLS = ['.spsa-track-wrap', '.spsa-value', '.spsa-delta'];
|
||||
|
||||
function flash(el) {
|
||||
el.classList.remove('live-flash');
|
||||
void el.offsetWidth;
|
||||
el.classList.add('live-flash');
|
||||
setTimeout(function () { el.classList.remove('live-flash'); }, 1500);
|
||||
}
|
||||
|
||||
function init() {
|
||||
|
||||
var list = document.getElementById('spsa-rows');
|
||||
var search = document.getElementById('spsa-filter');
|
||||
var order = document.getElementById('spsa-sort');
|
||||
var empty = document.getElementById('spsa-empty');
|
||||
|
||||
if (!list || !search || !order)
|
||||
return;
|
||||
|
||||
var rows = Array.prototype.slice.call(list.children);
|
||||
|
||||
function apply(keepScroll) {
|
||||
|
||||
var term = search.value.trim().toLowerCase();
|
||||
var shown = 0;
|
||||
|
||||
rows.sort(function (a, b) {
|
||||
if (order.value === 'drift')
|
||||
return parseFloat(b.dataset.drift) - parseFloat(a.dataset.drift);
|
||||
if (order.value === 'name')
|
||||
return a.dataset.name.localeCompare(b.dataset.name);
|
||||
return parseInt(a.dataset.index, 10) - parseInt(b.dataset.index, 10);
|
||||
});
|
||||
|
||||
rows.forEach(function (row) {
|
||||
var match = row.dataset.name.indexOf(term) !== -1;
|
||||
row.hidden = !match;
|
||||
shown += match ? 1 : 0;
|
||||
list.appendChild(row);
|
||||
});
|
||||
|
||||
// A new order or filter starts at the top; a refresh leaves the reader where they are
|
||||
if (!keepScroll)
|
||||
list.scrollTop = 0;
|
||||
|
||||
if (empty)
|
||||
empty.hidden = shown !== 0;
|
||||
}
|
||||
|
||||
function refresh(fresh) {
|
||||
|
||||
var incoming = {};
|
||||
Array.prototype.forEach.call(fresh.querySelectorAll('#spsa-rows .spsa-row'), function (row) {
|
||||
incoming[row.getAttribute('data-index')] = row;
|
||||
});
|
||||
|
||||
var moved = false;
|
||||
|
||||
rows.forEach(function (row) {
|
||||
|
||||
var next = incoming[row.getAttribute('data-index')];
|
||||
if (!next)
|
||||
return;
|
||||
|
||||
if (row.getAttribute('data-drift') !== next.getAttribute('data-drift')) {
|
||||
row.setAttribute('data-drift', next.getAttribute('data-drift'));
|
||||
moved = true;
|
||||
}
|
||||
|
||||
row.classList.toggle('at-bound', next.classList.contains('at-bound'));
|
||||
|
||||
CELLS.forEach(function (selector) {
|
||||
var current = row.querySelector(selector), latest = next.querySelector(selector);
|
||||
if (!current || !latest || current.innerHTML === latest.innerHTML)
|
||||
return;
|
||||
current.innerHTML = latest.innerHTML;
|
||||
if (selector !== '.spsa-track-wrap')
|
||||
flash(current);
|
||||
});
|
||||
});
|
||||
|
||||
// Sorted by how far they moved: the order itself may have changed
|
||||
if (moved && order.value === 'drift')
|
||||
apply(true);
|
||||
}
|
||||
|
||||
search.addEventListener('input', function () { apply(false); });
|
||||
order.addEventListener('change', function () { apply(false); });
|
||||
|
||||
document.addEventListener('live:patched', function (event) {
|
||||
if (event.detail && event.detail.fresh)
|
||||
refresh(event.detail.fresh);
|
||||
});
|
||||
}
|
||||
|
||||
if (document.readyState === 'loading')
|
||||
document.addEventListener('DOMContentLoaded', init);
|
||||
else
|
||||
init();
|
||||
|
||||
})();
|
||||
@@ -544,6 +544,138 @@ def spsa_optimal_values(workload):
|
||||
return '\n'.join(lines)
|
||||
|
||||
|
||||
def spsa_param_panel(workload):
|
||||
|
||||
# Data for the visual parameter panel on a Tune's page. Positions are
|
||||
# percentages along each parameter's [min, max] range, and every string is
|
||||
# formatted here so a locale can never turn a decimal point into a comma.
|
||||
|
||||
spsa = workload.spsa
|
||||
pairs = max(spsa['pairs_per'] * 2, 1)
|
||||
total = int(spsa['iterations'])
|
||||
complete = int(workload.games / pairs)
|
||||
|
||||
iteration = 1 + workload.games / pairs
|
||||
c_compression = iteration ** spsa['Gamma']
|
||||
r_compression = (spsa['A'] + iteration) ** spsa['Alpha']
|
||||
|
||||
def place(value, lo, span):
|
||||
return max(0.0, min(100.0, (value - lo) / span * 100.0))
|
||||
|
||||
# Maintain the original order, if there was one
|
||||
keys = sorted(
|
||||
spsa['parameters'].keys(),
|
||||
key=lambda x: spsa['parameters'][x].get('index', -1)
|
||||
)
|
||||
|
||||
entries = []
|
||||
for name in keys:
|
||||
|
||||
param = spsa['parameters'][name]
|
||||
is_float = bool(param['float'])
|
||||
|
||||
lo, hi = float(param['min']), float(param['max'])
|
||||
span = (hi - lo) or 1.0
|
||||
value, start = float(param['value']), float(param['start'])
|
||||
|
||||
now_pos = place(value, lo, span)
|
||||
start_pos = place(start, lo, span)
|
||||
|
||||
c = max(param['c'] / c_compression, 0.00 if is_float else 0.50)
|
||||
r = param['a'] / r_compression / c ** 2
|
||||
|
||||
fmt = '%.4f' if is_float else '%d'
|
||||
dfmt = '%+.4f' if is_float else '%+d'
|
||||
|
||||
shown_value = value if is_float else round(value)
|
||||
shown_start = start if is_float else round(start)
|
||||
|
||||
bound = ''
|
||||
if now_pos <= 1.0: bound = 'min'
|
||||
elif now_pos >= 99.0: bound = 'max'
|
||||
|
||||
entries.append({
|
||||
'name' : name,
|
||||
'value' : fmt % shown_value,
|
||||
'start' : fmt % shown_start,
|
||||
'min' : fmt % lo,
|
||||
'max' : fmt % hi,
|
||||
'delta' : dfmt % (shown_value - shown_start),
|
||||
'moved' : shown_value != shown_start,
|
||||
'bound' : bound,
|
||||
'now' : '%.2f' % now_pos,
|
||||
'from' : '%.2f' % start_pos,
|
||||
'left' : '%.2f' % min(now_pos, start_pos),
|
||||
'width' : '%.2f' % abs(now_pos - start_pos),
|
||||
'drift' : '%.3f' % (abs(value - start) / span * 100.0),
|
||||
'c' : '%.4f' % c,
|
||||
'r' : '%.4f' % r,
|
||||
})
|
||||
|
||||
return {
|
||||
'params' : entries,
|
||||
'count' : len(entries),
|
||||
'moved' : sum(1 for e in entries if e['moved']),
|
||||
'complete' : complete,
|
||||
'iterations' : total,
|
||||
'pct' : '%.1f' % (max(0.0, min(100.0, complete / total * 100.0)) if total else 0.0),
|
||||
'games' : int(workload.games),
|
||||
}
|
||||
|
||||
def spsa_history_chart(workload):
|
||||
|
||||
# Data for the Tune page's history chart, drawn in the browser by spsa_chart.js
|
||||
# Rows are [ games, value, value, ... ], in the same order as the parameter panel
|
||||
|
||||
spsa = workload.spsa
|
||||
keys = sorted(spsa['parameters'].keys(), key=lambda x: spsa['parameters'][x].get('index', -1))
|
||||
params = [spsa['parameters'][key] for key in keys]
|
||||
|
||||
start = [float(p['start']) for p in params]
|
||||
current = [float(p['value']) for p in params]
|
||||
games = int(workload.games)
|
||||
|
||||
stored = OpenBench.utils.load_spsa_history(workload)
|
||||
rows = []
|
||||
|
||||
if stored:
|
||||
column = { name : index for index, name in enumerate(stored.get('names', [])) }
|
||||
for point in stored.get('points', []):
|
||||
row = [int(point[0])]
|
||||
for key, fallback in zip(keys, start):
|
||||
index = column.get(key)
|
||||
row.append(point[1 + index] if index is not None and 1 + index < len(point) else fallback)
|
||||
rows.append(row)
|
||||
|
||||
# The line starts at the start values, and ends on the current state
|
||||
if not rows or rows[0][0] != 0:
|
||||
rows.insert(0, [0] + start)
|
||||
if rows[-1][0] == games and games > 0:
|
||||
rows[-1] = [games] + current
|
||||
elif rows[-1][0] < games:
|
||||
rows.append([games] + current)
|
||||
|
||||
# Never send more than a few hundred points to the browser
|
||||
limit = 200
|
||||
if len(rows) > limit:
|
||||
step = (len(rows) - 1) / float(limit - 1)
|
||||
keep = sorted(set(int(round(i * step)) for i in range(limit)) | { len(rows) - 1 })
|
||||
rows = [rows[i] for i in keep]
|
||||
|
||||
data = {
|
||||
'names' : keys,
|
||||
'start' : start,
|
||||
'min' : [float(p['min']) for p in params],
|
||||
'max' : [float(p['max']) for p in params],
|
||||
'integer' : [not p['float'] for p in params],
|
||||
'points' : [[row[0]] + [round(float(v), 4) for v in row[1:]] for row in rows],
|
||||
'recorded' : bool(stored),
|
||||
'games' : games,
|
||||
}
|
||||
|
||||
payload = html.escape(json.dumps(data, separators=(',', ':')), quote=True)
|
||||
return mark_safe('<div class="spsa-chart" data-chart="%s"></div>' % payload)
|
||||
|
||||
def book_download_link(workload):
|
||||
if workload.book_name in OpenBench.config.OPENBENCH_CONFIG['books']:
|
||||
return OpenBench.config.OPENBENCH_CONFIG['books'][workload.book_name]['source']
|
||||
@@ -609,6 +741,8 @@ register.filter('spsa_param_digest', spsa_param_digest)
|
||||
register.filter('spsa_param_digest_headers', spsa_param_digest_headers)
|
||||
register.filter('spsa_original_input', spsa_original_input)
|
||||
register.filter('spsa_optimal_values', spsa_optimal_values)
|
||||
register.filter('spsa_param_panel', spsa_param_panel)
|
||||
register.filter('spsa_history_chart', spsa_history_chart)
|
||||
|
||||
register.filter('book_download_link', book_download_link)
|
||||
register.filter('network_download_link', network_download_link)
|
||||
|
||||
@@ -57,7 +57,27 @@ def progress_info(test):
|
||||
else:
|
||||
fraction, tone = 0.0, 'neutral'
|
||||
|
||||
return { 'pct' : int(max(0.0, min(1.0, fraction)) * 100), 'tone' : tone }
|
||||
info = { 'pct' : int(max(0.0, min(1.0, fraction)) * 100), 'tone' : tone }
|
||||
|
||||
# Data for the LLR gauge: the track runs lower -> upper bound, the fill
|
||||
# grows from LLR = 0 towards the current LLR. Strings are formatted here
|
||||
# so locale settings can never turn a decimal point into a comma.
|
||||
|
||||
if lower < 0 < upper:
|
||||
span = upper - lower
|
||||
pos = max(0.0, min(1.0, (current - lower) / span)) * 100
|
||||
zero = (0.0 - lower) / span * 100
|
||||
info.update({
|
||||
'gauge' : True,
|
||||
'llr' : '%.2f' % current,
|
||||
'lower' : '%.2f' % lower,
|
||||
'upper' : '%.2f' % upper,
|
||||
'zero' : '%.1f' % zero,
|
||||
'left' : '%.1f' % min(pos, zero),
|
||||
'width' : '%.1f' % abs(pos - zero),
|
||||
})
|
||||
|
||||
return info
|
||||
|
||||
if test.max_games:
|
||||
fraction = test.games / float(test.max_games)
|
||||
|
||||
@@ -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)
|
||||
+6
-1
@@ -18,10 +18,14 @@
|
||||
# #
|
||||
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
|
||||
|
||||
import django.urls, OpenBench.views
|
||||
import django.urls, OpenBench.views, OpenBench.seo
|
||||
|
||||
urlpatterns = [
|
||||
|
||||
# Files for search engines
|
||||
django.urls.path(r'robots.txt', OpenBench.seo.robots_txt),
|
||||
django.urls.path(r'sitemap.xml', OpenBench.seo.sitemap_xml),
|
||||
|
||||
# Links for account management
|
||||
django.urls.path(r'register/', OpenBench.views.register),
|
||||
django.urls.path(r'login/', OpenBench.views.login),
|
||||
@@ -94,6 +98,7 @@ urlpatterns = [
|
||||
django.urls.path(r'api/buildinfo/', OpenBench.views.api_build_info),
|
||||
django.urls.path(r'api/pgns/<int:pgn_id>/', OpenBench.views.api_pgns),
|
||||
django.urls.path(r'api/test/<int:id>/llr-history/', OpenBench.views.test_llr_history),
|
||||
django.urls.path(r'api/quick-search/', OpenBench.views.api_quick_search),
|
||||
|
||||
# Redirect anything else to the Index
|
||||
django.urls.path(r'', OpenBench.views.index),
|
||||
|
||||
@@ -286,6 +286,61 @@ def get_llr_history(test, max_points=LLR_HISTORY_SAMPLE_POINTS):
|
||||
|
||||
return compact_history
|
||||
|
||||
SPSA_HISTORY_MAX_POINTS = 1500
|
||||
|
||||
def spsa_history_path(test_id):
|
||||
return os.path.join(MEDIA_ROOT, 'spsa_history', '%d.json' % (test_id))
|
||||
|
||||
def spsa_param_names(test):
|
||||
|
||||
# Maintain the original order, if there was one
|
||||
return sorted(
|
||||
test.spsa['parameters'].keys(),
|
||||
key=lambda x: test.spsa['parameters'][x].get('index', -1)
|
||||
)
|
||||
|
||||
def load_spsa_history(test):
|
||||
|
||||
# { 'names' : [ ... ], 'points' : [ [ games, value, value, ... ], ... ] }
|
||||
path = spsa_history_path(test.id)
|
||||
if not os.path.exists(path):
|
||||
return None
|
||||
|
||||
try:
|
||||
with open(path) as fin:
|
||||
history = json.load(fin)
|
||||
return history if history.get('points') else None
|
||||
except Exception:
|
||||
return None
|
||||
|
||||
def record_spsa_history(test):
|
||||
|
||||
names = spsa_param_names(test)
|
||||
history = load_spsa_history(test) or {}
|
||||
|
||||
# Parameters were renamed, or reordered. Start over
|
||||
if history.get('names') != names:
|
||||
history = { 'names' : names, 'points' : [] }
|
||||
|
||||
point = [int(test.games)]
|
||||
point += [round(float(test.spsa['parameters'][name]['value']), 4) for name in names]
|
||||
|
||||
points = history['points']
|
||||
if points and points[-1][0] == point[0]:
|
||||
points[-1] = point
|
||||
else:
|
||||
points.append(point)
|
||||
|
||||
# Keep the file bounded: drop every other point, but always keep the latest
|
||||
if len(points) > SPSA_HISTORY_MAX_POINTS:
|
||||
last = points[-1]
|
||||
points = points[::2]
|
||||
if points[-1] is not last:
|
||||
points.append(last)
|
||||
|
||||
history['points'] = points
|
||||
write_json_file(spsa_history_path(test.id), history)
|
||||
|
||||
def extract_option(options, option):
|
||||
|
||||
match = re.search(r'(?<={0}=")[^"]*'.format(option), options)
|
||||
@@ -552,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
|
||||
@@ -575,6 +636,7 @@ def update_test(request, machine):
|
||||
|
||||
test = Test.objects.select_for_update().get(id=test_id)
|
||||
should_record_llr = False
|
||||
should_record_spsa = False
|
||||
|
||||
if test.finished or test.deleted:
|
||||
return { 'stop' : True }
|
||||
@@ -625,6 +687,7 @@ def update_test(request, machine):
|
||||
param['value'] = max(param['min'], min(param['max'], x))
|
||||
|
||||
test.finished = test.games >= 2 * test.spsa['pairs_per'] * test.spsa['iterations']
|
||||
should_record_spsa = True
|
||||
|
||||
elif test.test_mode == 'DATAGEN':
|
||||
|
||||
@@ -633,9 +696,19 @@ def update_test(request, machine):
|
||||
|
||||
test.save()
|
||||
|
||||
if should_record_spsa:
|
||||
try:
|
||||
record_spsa_history(test)
|
||||
except Exception:
|
||||
pass # History is a nicety, and must never fail a result upload
|
||||
|
||||
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,
|
||||
|
||||
@@ -585,6 +585,41 @@ def test_llr_history(request, id):
|
||||
|
||||
return HttpResponse(str(llr_history_graph(test)), content_type='text/plain; charset=utf-8')
|
||||
|
||||
def api_quick_search(request):
|
||||
|
||||
## Feeds the Ctrl+K palette: up to eight workloads that match a branch name,
|
||||
## an author, an engine, or a workload id, newest first.
|
||||
|
||||
if OPENBENCH_CONFIG['require_login_to_view'] and not request.user.is_authenticated:
|
||||
return JsonResponse({ 'tests' : [] }, status=403)
|
||||
|
||||
from OpenBench.templatetags.mytags import prettyName
|
||||
from OpenBench.templatetags.uitags import test_status
|
||||
|
||||
query = request.GET.get('q', '').strip().lstrip('#')[:64]
|
||||
if not query:
|
||||
return JsonResponse({ 'tests' : [] })
|
||||
|
||||
match = Q(dev__name__icontains=query) | Q(author__icontains=query) | Q(dev_engine__icontains=query)
|
||||
if query.isdigit() and len(query) <= 9:
|
||||
match |= Q(id=int(query))
|
||||
|
||||
found = list(Test.objects.select_related('dev').filter(match).exclude(deleted=True).order_by('-id')[:8])
|
||||
|
||||
# An exact workload id is always the first hit
|
||||
if query.isdigit():
|
||||
found.sort(key=lambda test: str(test.id) != query)
|
||||
|
||||
return JsonResponse({ 'tests' : [{
|
||||
'id' : test.id,
|
||||
'name' : prettyName(test.dev.name),
|
||||
'author' : test.author.capitalize(),
|
||||
'engine' : test.dev_engine,
|
||||
'tc' : test.dev_time_control,
|
||||
'status' : test_status(test),
|
||||
'url' : '/%s/%d/' % ('tune' if test.test_mode == 'SPSA' else 'test', test.id),
|
||||
} for test in found] })
|
||||
|
||||
def create_test(request):
|
||||
return create_workload(request, 'TEST')
|
||||
|
||||
@@ -789,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)
|
||||
|
||||
|
||||
@@ -0,0 +1,82 @@
|
||||
<!-- Quick search palette ( Ctrl+K ). Driven by palette.js, styled by palette.css.
|
||||
Without JavaScript the Search button in the top bar still opens /search. -->
|
||||
|
||||
<div id="palette" role="dialog" aria-modal="true" aria-label="Quick search" hidden>
|
||||
|
||||
<div class="pl-backdrop"></div>
|
||||
|
||||
<div class="pl-panel">
|
||||
|
||||
<div class="pl-field">
|
||||
<i class="fa-solid fa-magnifying-glass pl-glass" aria-hidden="true"></i>
|
||||
<input class="pl-input" type="text" role="combobox" aria-expanded="true" aria-controls="pl-list"
|
||||
aria-autocomplete="list" aria-label="Search" autocomplete="off" autocapitalize="off"
|
||||
spellcheck="false" enterkeyhint="go" placeholder="Search tests, pages and actions">
|
||||
</div>
|
||||
|
||||
<ul class="pl-list" id="pl-list" role="listbox" aria-label="Results"></ul>
|
||||
|
||||
<div class="pl-foot" aria-hidden="true">
|
||||
<span><kbd>↑</kbd><kbd>↓</kbd>move</span>
|
||||
<span><kbd>↵</kbd>open</span>
|
||||
<span><kbd>esc</kbd>close</span>
|
||||
</div>
|
||||
|
||||
<div class="pl-sr" aria-live="polite"></div>
|
||||
|
||||
</div>
|
||||
|
||||
<!-- Pages and actions. Only the featured ones are listed before anything is typed -->
|
||||
<ul id="palette-source" hidden>
|
||||
|
||||
<li data-group="Go to" data-href="/index" data-icon="fa-house" data-keywords="home tests overview" data-featured>Index</li>
|
||||
<li data-group="Go to" data-href="/greens" data-icon="fa-heart" data-keywords="passed wins" data-featured>Greens</li>
|
||||
<li data-group="Go to" data-href="/search" data-icon="fa-sliders" data-keywords="filter find tests" data-featured>Advanced search</li>
|
||||
<li data-group="Go to" data-href="/machines" data-icon="fa-microchip" data-keywords="workers clients fleet" data-featured>Machines</li>
|
||||
<li data-group="Go to" data-href="/users" data-icon="fa-users" data-keywords="people contributors">Users</li>
|
||||
<li data-group="Go to" data-href="/events" data-icon="fa-circle-exclamation" data-keywords="log actions">Events</li>
|
||||
<li data-group="Go to" data-href="/errors" data-icon="fa-triangle-exclamation" data-keywords="crash failures log">Errors</li>
|
||||
<li data-group="Go to" data-href="/networks" data-icon="fa-circle-nodes" data-keywords="nets nnue">Networks</li>
|
||||
|
||||
<li data-group="Create" data-href="/newTest" data-icon="fa-plus" data-keywords="new sprt test" data-featured>Create test</li>
|
||||
<li data-group="Create" data-href="/newTune" data-icon="fa-vial" data-keywords="new spsa tune" data-featured>Create tune</li>
|
||||
<li data-group="Create" data-href="/newDatagen" data-icon="fa-database" data-keywords="new data generation">Create datagen</li>
|
||||
<li data-group="Create" data-href="/newNetwork" data-icon="fa-upload" data-keywords="new network net nnue">Upload net</li>
|
||||
|
||||
{% if user.is_authenticated %}
|
||||
<li data-group="Account" data-href="/profile/" data-icon="fa-user" data-keywords="settings password email">Profile</li>
|
||||
<li data-group="Account" data-href="/logout/" data-icon="fa-right-from-bracket" data-keywords="sign out">Log out</li>
|
||||
{% else %}
|
||||
<li data-group="Account" data-href="/login" data-icon="fa-right-to-bracket" data-keywords="sign in">Log in</li>
|
||||
<li data-group="Account" data-href="/register" data-icon="fa-registered" data-keywords="sign up account">Register</li>
|
||||
{% endif %}
|
||||
|
||||
<li data-group="Links" data-href="{{config.client_repo_url}}" data-icon="fa-brands fa-github" data-keywords="source client code" data-external>OpenBench on GitHub</li>
|
||||
{% for engine, data in config.engines.items %}
|
||||
<li data-group="Links" data-href="{{data.source}}" data-icon="fa-chess-knight" data-keywords="engine source repository" data-external>{{engine}} source</li>
|
||||
{% endfor %}
|
||||
|
||||
</ul>
|
||||
|
||||
<!-- Hands a free text search over to the existing /search/ page, with every filter left open -->
|
||||
<form id="palette-search" method="POST" action="/search/" hidden>
|
||||
{% csrf_token %}
|
||||
<input type="hidden" name="keywords" value="">
|
||||
<input type="hidden" name="author" value="">
|
||||
<input type="hidden" name="engine" value="">
|
||||
<input type="hidden" name="opening-book" value="">
|
||||
<input type="hidden" name="test-mode" value="">
|
||||
<input type="hidden" name="syzygy-wdl" value="">
|
||||
<input type="hidden" name="tc-type" value="">
|
||||
<input type="hidden" name="tc-value-select" value="=">
|
||||
<input type="hidden" name="tc-value-input" value="">
|
||||
<input type="hidden" name="threads-select" value=">=">
|
||||
<input type="hidden" name="threads-input" value="1">
|
||||
<input type="hidden" name="show-greens" value="">
|
||||
<input type="hidden" name="show-blues" value="">
|
||||
<input type="hidden" name="show-yellows" value="">
|
||||
<input type="hidden" name="show-reds" value="">
|
||||
<input type="hidden" name="show-stopped" value="">
|
||||
</form>
|
||||
|
||||
</div>
|
||||
@@ -1,12 +1,18 @@
|
||||
{% load mytags uitags %}
|
||||
<td class="col-author"><a href="/user/{{test.author}}">{{test.author|capfirst|slice:":6"}}</a></td>
|
||||
<td class="col-author"><a href="/user/{{test.author}}" title="{{test.author|capfirst}}">{{test.author|capfirst}}</a></td>
|
||||
<td class="col-engine">{{test.dev_engine}}</td>
|
||||
<td class="col-test">
|
||||
<a href="{{test|workload_url}}">{{test|prettyDevName}}</a>
|
||||
{% if test.error %}<span class="flag flag-error" title="Crash or illegal move">crash</span>{% endif %}
|
||||
{% if test|test_is_fischer %}<span class="flag flag-frc" title="Fischer random chess">frc</span>{% endif %}
|
||||
{% with progress=test|progress_info %}
|
||||
{% if progress %}
|
||||
{% if progress.gauge %}
|
||||
<div class="llr llr-{{ progress.tone }}" role="meter" aria-label="LLR" aria-valuemin="{{ progress.lower }}" aria-valuemax="{{ progress.upper }}" aria-valuenow="{{ progress.llr }}" title="LLR {{ progress.llr }} (bounds {{ progress.lower }} to {{ progress.upper }})">
|
||||
<span class="llr-fill" style="left: {{ progress.left }}%; width: {{ progress.width }}%"></span>
|
||||
<span class="llr-zero" style="left: {{ progress.zero }}%"></span>
|
||||
</div>
|
||||
<div class="llr-scale"><span>{{ progress.lower }}</span><b>{{ progress.llr }}</b><span>{{ progress.upper }}</span></div>
|
||||
{% elif progress %}
|
||||
<div class="ob-progress ob-progress-{{ progress.tone }}" role="progressbar" aria-valuemin="0" aria-valuemax="100" aria-valuenow="{{ progress.pct }}" title="{{ progress.pct }}%"><span style="width: {{ progress.pct }}%"></span></div>
|
||||
{% endif %}
|
||||
{% endwith %}
|
||||
@@ -17,4 +23,4 @@
|
||||
{% if test|test_is_time_odds %}<span class="flag flag-time" title="Time odds">time odds</span>{% endif %}
|
||||
{% if test|test_is_smp_odds %}<span class="flag flag-smp" title="Thread odds">thread odds</span>{% endif %}
|
||||
</td>
|
||||
<td class='statblock statblock-{{test|testResultColour}} col-result'><strong>{{test|shortStatBlock|linebreaksbr}}</strong></td>
|
||||
<td class='statblock statblock-{{test|testResultColour}} state-{{ test|test_status }} col-result'><strong>{{test|shortStatBlock|linebreaksbr}}</strong></td>
|
||||
@@ -7,7 +7,7 @@
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<meta name="theme-color" content="#0B0E14">
|
||||
<meta name="theme-color" content="#14161A">
|
||||
<meta name="color-scheme" content="dark">
|
||||
|
||||
<link rel="icon" type="image/svg+xml" href="{% static 'logo.svg' %}?{{ static_version }}">
|
||||
@@ -17,20 +17,39 @@
|
||||
<link rel="stylesheet" href="{% static 'paging.css' %}?{{ static_version }}">
|
||||
<link rel="stylesheet" href="{% static 'ux.css' %}?{{ static_version }}">
|
||||
<link rel="stylesheet" href="{% static 'board.css' %}?{{ static_version }}">
|
||||
<link rel="stylesheet" href="{% static 'refresh.css' %}?{{ static_version }}">
|
||||
<link rel="stylesheet" href="{% static 'palette.css' %}?{{ static_version }}">
|
||||
<link rel="stylesheet" href="{% static 'live.css' %}?{{ static_version }}">
|
||||
|
||||
<link href='https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.2.0/css/all.min.css' rel='stylesheet'>
|
||||
|
||||
<link rel="preconnect" href="https://fonts.googleapis.com">
|
||||
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
|
||||
<link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700&family=JetBrains+Mono:wght@400;500;600&display=swap" rel="stylesheet">
|
||||
<link href="https://fonts.googleapis.com/css2?family=Instrument+Sans:wght@400;500;600;700&family=JetBrains+Mono:wght@400;500;600&display=swap" rel="stylesheet">
|
||||
|
||||
<title>RektBench</title>
|
||||
<title>{% block title %}RektBench - Distributed SPRT Testing for Chess Engines{% endblock %}</title>
|
||||
<meta name="description" content="{% block description %}RektBench is a distributed SPRT testing framework for chess engines: live tests, results, networks and worker machines.{% endblock %}">
|
||||
<meta name="robots" content="{% block robots %}index, follow{% endblock %}">
|
||||
<link rel="canonical" href="{{ request.scheme }}://{{ request.get_host }}{{ request.path }}">
|
||||
|
||||
<meta property="og:site_name" content="RektBench">
|
||||
<meta property="og:type" content="website">
|
||||
<meta property="og:title" content="RektBench">
|
||||
<meta property="og:description" content="Distributed SPRT testing framework for chess engines.">
|
||||
<meta property="og:url" content="{{ request.scheme }}://{{ request.get_host }}{{ request.path }}">
|
||||
<meta name="twitter:card" content="summary">
|
||||
|
||||
<script type="application/ld+json">
|
||||
{"@context": "https://schema.org", "@type": "WebSite", "name": "RektBench", "alternateName": "Rekt Bench", "url": "{{ request.scheme }}://{{ request.get_host }}/"}
|
||||
</script>
|
||||
|
||||
{% block scripts %}
|
||||
{% endblock %}
|
||||
|
||||
<script src="{% static 'ui.js' %}?{{ static_version }}" defer></script>
|
||||
<script src="{% static 'ux.js' %}?{{ static_version }}" defer></script>
|
||||
<script src="{% static 'palette.js' %}?{{ static_version }}" defer></script>
|
||||
<script src="{% static 'live.js' %}?{{ static_version }}" defer></script>
|
||||
|
||||
<script>
|
||||
document.addEventListener('DOMContentLoaded', function() {
|
||||
@@ -46,7 +65,8 @@
|
||||
};
|
||||
|
||||
for (var i = 0; i < timestamps.length; i++) {
|
||||
var date = new Date(1000 * timestamps[i].innerHTML);
|
||||
var epoch = timestamps[i].getAttribute('data-epoch');
|
||||
var date = new Date(1000 * (epoch !== null ? epoch : timestamps[i].innerHTML));
|
||||
timestamps[i].innerHTML = date.toLocaleString(undefined, options);
|
||||
}
|
||||
}
|
||||
@@ -96,8 +116,8 @@
|
||||
<div class="topbar-spacer"></div>
|
||||
|
||||
<nav class="topbar-actions" aria-label="Quick actions">
|
||||
<a class="topbar-btn" href="/search" title="Search tests">
|
||||
<i class="fa-solid fa-magnifying-glass fa-fw"></i><span>Search</span>
|
||||
<a class="topbar-btn" id="palette-open" href="/search" title="Search tests" aria-keyshortcuts="Control+K Meta+K">
|
||||
<i class="fa-solid fa-magnifying-glass fa-fw"></i><span>Search</span><kbd class="topbar-kbd" aria-hidden="true">Ctrl K</kbd>
|
||||
</a>
|
||||
<a class="topbar-btn topbar-btn-primary" href="/newTest" title="Create a new test">
|
||||
<i class="fa-solid fa-plus fa-fw"></i><span>Create Test</span>
|
||||
@@ -222,5 +242,7 @@
|
||||
|
||||
<div id="toast" role="status" aria-live="polite"></div>
|
||||
|
||||
{% include "OpenBench/Blocks/palette.html" %}
|
||||
|
||||
</body>
|
||||
</html>
|
||||
@@ -24,13 +24,6 @@
|
||||
<div class="stat-label">Pending approval</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="stat-card stat-purple">
|
||||
<span class="stat-icon"><i class="fa-solid fa-hammer"></i></span>
|
||||
<div>
|
||||
<div class="stat-value">{{ awaiting|length }}</div>
|
||||
<div class="stat-label">Awaiting artifacts</div>
|
||||
</div>
|
||||
</div>
|
||||
{% if fleet %}
|
||||
<div class="stat-card stat-green">
|
||||
<span class="stat-icon"><i class="fa-solid fa-microchip"></i></span>
|
||||
|
||||
@@ -5,6 +5,10 @@
|
||||
|
||||
{% block scripts %}
|
||||
<link rel="stylesheet" href="{% static 'workload.css' %}?{{ static_version }}">
|
||||
<link rel="stylesheet" href="{% static 'spsa_panel.css' %}?{{ static_version }}">
|
||||
<link rel="stylesheet" href="{% static 'spsa_chart.css' %}?{{ static_version }}">
|
||||
<script src="{% static 'spsa_chart.js' %}?{{ static_version }}" defer></script>
|
||||
<script src="{% static 'spsa_panel.js' %}?{{ static_version }}" defer></script>
|
||||
<script src="{% static 'copy_text.js' %}?{{ static_version }}"></script>
|
||||
<script src="{% static 'llr_history.js' %}?{{ static_version }}" defer></script>
|
||||
{% endblock %}
|
||||
@@ -13,14 +17,15 @@
|
||||
|
||||
{% block content %}
|
||||
|
||||
<div class="workload-container">
|
||||
<div class="workload-container{% if type == "TUNE" %} tune-page{% endif %}">
|
||||
{% if type == "TUNE" %}<div class="tune-side">{% endif %}
|
||||
|
||||
<div id="config" class="card">
|
||||
<header class="card-head"><h2 class="card-title">Configuration</h2></header>
|
||||
{% if type == "TUNE" %}<details id="config" class="card config-fold"><summary><span class="card-title">Settings</span><span class="config-hint">Engine, network, book</span></summary>{% else %}<div id="config" class="card">{% endif %}
|
||||
{% if type != "TUNE" %}<header class="card-head"><h2 class="card-title">Configuration</h2></header>{% endif %}
|
||||
<table class="test-config left-align wrappable">
|
||||
|
||||
<tr><td class="td-label">Author</td><td>{{workload.author|capfirst}}</td></tr>
|
||||
<tr><td class="td-label">Creation</td><td class="timestamp">{{workload.creation|date:'U'}}</td></tr>
|
||||
<tr><td class="td-label">Creation</td><td><time class="timestamp" data-epoch="{{workload.creation|date:'U'}}" datetime="{{workload.creation|date:'c'}}">{{workload.creation|date:'Y-m-d H:i'}}</time></td></tr>
|
||||
|
||||
<!-- All of the Dev Engine ( or Sole Engine ) information -->
|
||||
<tr><td class="td-label">{{dev_text}} Source</td><td><a href="{{workload.dev_repo}}">{{workload.dev_repo}}</a></td></tr>
|
||||
@@ -67,7 +72,7 @@
|
||||
{% endif %}
|
||||
|
||||
</table>
|
||||
</div>
|
||||
{% if type == "TUNE" %}</details>{% else %}</div>{% endif %}
|
||||
|
||||
<div id="actions" class="card">
|
||||
<header class="card-head"><h2 class="card-title">Actions</h2></header>
|
||||
@@ -212,8 +217,72 @@
|
||||
|
||||
<!-- SPSA Paramater Summary, for Tunes -->
|
||||
{% if type == "TUNE" %}
|
||||
<div id="parameters" class="card">
|
||||
<header class="card-head"><h2 class="card-title">SPSA Parameters</h2></header>
|
||||
</div><!-- /tune-side -->
|
||||
<div class="tune-main">
|
||||
{% with panel=workload|spsa_param_panel %}
|
||||
<section id="spsa-panel" class="card spsa-panel">
|
||||
<header class="card-head"><h2 class="card-title">Tuning progress</h2></header>
|
||||
|
||||
<div class="spsa-summary">
|
||||
<div class="spsa-iter">
|
||||
<span class="spsa-big">{{ panel.complete }}</span>
|
||||
<span class="spsa-of">of {{ panel.iterations }} iterations</span>
|
||||
</div>
|
||||
<div class="spsa-bar" role="progressbar" aria-label="Iterations completed" aria-valuemin="0" aria-valuemax="100" aria-valuenow="{{ panel.pct }}"><span style="width: {{ panel.pct }}%"></span></div>
|
||||
<dl class="spsa-facts">
|
||||
<div><dt>Parameters</dt><dd>{{ panel.count }}</dd></div>
|
||||
<div><dt>Moved</dt><dd>{{ panel.moved }}</dd></div>
|
||||
<div><dt>Games</dt><dd>{{ panel.games|insertCommas }}</dd></div>
|
||||
</dl>
|
||||
</div>
|
||||
|
||||
<div class="spsa-history">
|
||||
<div class="spsa-history-head">
|
||||
<h3>Movement since the start</h3>
|
||||
<p>Each line is one parameter, as a share of its allowed range. Point at a name below to follow it, or click it to keep it on the chart.</p>
|
||||
</div>
|
||||
{{ workload|spsa_history_chart }}
|
||||
</div>
|
||||
|
||||
<div class="spsa-tools">
|
||||
<input id="spsa-filter" type="search" placeholder="Filter parameters" aria-label="Filter parameters by name" autocomplete="off">
|
||||
<select id="spsa-sort" aria-label="Sort parameters">
|
||||
<option value="index">Original order</option>
|
||||
<option value="drift">Moved the most</option>
|
||||
<option value="name">Name</option>
|
||||
</select>
|
||||
</div>
|
||||
|
||||
<ol id="spsa-rows" class="spsa-rows">
|
||||
{% for p in panel.params %}
|
||||
<li class="spsa-row{% if p.bound %} at-bound{% endif %}" data-name="{{ p.name|lower }}" data-drift="{{ p.drift }}" data-index="{{ forloop.counter0 }}">
|
||||
<button type="button" class="spsa-name" aria-pressed="false" title="Show on the chart">{{ p.name }}</button>
|
||||
<div class="spsa-track-wrap">
|
||||
<div class="spsa-track" role="img" aria-label="{{ p.name }} is {{ p.value }}, within {{ p.min }} to {{ p.max }}, started at {{ p.start }}{% if p.bound %}, at its {{ p.bound }} limit{% endif %}" title="Start {{ p.start }}, now {{ p.value }}, C {{ p.c }}, R {{ p.r }}{% if p.bound %}. At its {{ p.bound }} limit.{% endif %}">
|
||||
<span class="spsa-drift" style="left: {{ p.left }}%; width: {{ p.width }}%"></span>
|
||||
<span class="spsa-start" style="left: {{ p.from }}%"></span>
|
||||
<span class="spsa-now" style="left: {{ p.now }}%"></span>
|
||||
</div>
|
||||
<div class="spsa-scale"><span>{{ p.min }}</span><span>{{ p.max }}</span></div>
|
||||
</div>
|
||||
<span class="spsa-value">{{ p.value }}</span>
|
||||
<span class="spsa-delta">{% if p.moved %}{{ p.delta }}{% else %}unchanged{% endif %}</span>
|
||||
</li>
|
||||
{% endfor %}
|
||||
</ol>
|
||||
<p id="spsa-empty" class="spsa-empty" hidden>No parameter matches that name.</p>
|
||||
|
||||
<div class="spsa-key">
|
||||
<span><i class="k-start"></i>Start value</span>
|
||||
<span><i class="k-now"></i>Current value</span>
|
||||
<span><i class="k-limit"></i>At a limit of its range</span>
|
||||
</div>
|
||||
</section>
|
||||
{% endwith %}
|
||||
|
||||
<details id="parameters" class="card config-fold">
|
||||
<summary><span class="card-title">Parameter details</span><span class="config-hint">Start, limits, C and R</span></summary>
|
||||
|
||||
<table class="stripes wrappable">
|
||||
|
||||
<tr class="table-header">
|
||||
@@ -234,11 +303,11 @@
|
||||
</tr>
|
||||
{% endfor %}
|
||||
</table>
|
||||
</div>
|
||||
</details>
|
||||
{% endif %}
|
||||
|
||||
<div id="results" class="card">
|
||||
<header class="card-head"><h2 class="card-title">Results by Machine</h2></header>
|
||||
{% if type == "TUNE" %}<details id="results" class="card config-fold"><summary><span class="card-title">Results by Machine</span><span class="config-hint">{{ results|length }} machine{{ results|length|pluralize }}, games and results</span></summary>{% else %}<div id="results" class="card">
|
||||
<header class="card-head"><h2 class="card-title">Results by Machine</h2></header>{% endif %}
|
||||
<table class="stripes wrappable">
|
||||
<tr class="table-header">
|
||||
<th>#</th>
|
||||
@@ -257,7 +326,7 @@
|
||||
<tr {% if result.active %} class="active-highlight" {% endif %}>
|
||||
<td><a href="/machines/{{result.data.machine.id}}">{{result.data.machine.id}}</a></td>
|
||||
<td>{{result.data.machine.user.username|capfirst}}</td>
|
||||
<td class="timestamp">{{result.data.updated|date:'U'}}</td>
|
||||
<td><time class="timestamp" data-epoch="{{result.data.updated|date:'U'}}" datetime="{{result.data.updated|date:'c'}}">{{result.data.updated|date:'Y-m-d H:i'}}</time></td>
|
||||
<td class="numeric">{{result.data.games}}</td>
|
||||
<td class="numeric">{{result.data.wins}}</td>
|
||||
<td class="numeric">{{result.data.losses}}</td>
|
||||
@@ -267,8 +336,9 @@
|
||||
</tr>
|
||||
{% endfor %}
|
||||
</table>
|
||||
</div>
|
||||
{% if type == "TUNE" %}</details>{% else %}</div>{% endif %}
|
||||
{% if type == "TUNE" %}</div><!-- /tune-main -->{% endif %}
|
||||
|
||||
</div>
|
||||
|
||||
{% endblock %}
|
||||
{% endblock %}
|
||||
@@ -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