Compare commits

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

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

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

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

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

What no preset can fill in is reported instead of guessed. Includes the unit
tests, which run without Django.
2026-10-13 21:28:35 +02:00
claude 0122ede0f6 Pipelines: a visual editor. The flow is drawn on a canvas, a + on every step adds what happens next, and the settings sit in a side panel like the Create Test form 2026-10-13 18:59:54 +02:00
claude faf719ca31 Pipelines: a preview endpoint that draws and checks a graph while it is being built 2026-10-13 18:58:35 +02:00
claude 2ed44ca053 Pipelines: create and edit pipelines from the web UI 2026-10-11 22:54:41 +02:00
claude 011add1f23 Wire the pipeline pages in: routes, sidebar link, styles, and the chip on a test's page 2026-10-11 22:37:47 +02:00
claude ea1fed2627 Add tests for the pipeline pages: permission matrix, actions, pages, live signature, chip 2026-10-11 22:37:12 +02:00
claude edfc43a2be Pipeline pages: views for the list, the pipeline and the run
Permissions decided in one place (can_manage), every change is a POST,
and every decision leaves an event behind.
2026-10-11 22:36:22 +02:00
claude 860bb6f0d2 Pipeline pages: pipeline and run templates 2026-10-11 22:35:35 +02:00
claude 752650fd31 Pipeline pages: end the new files with a newline 2026-10-11 22:34:57 +02:00
claude 55c38e6180 Pipeline pages: list view, template and live-update script
Restores the first part of the pipeline pages commit that was lost in the
rebase: the pipelines list template and the run page's live-update script.
2026-10-11 22:34:45 +02:00
claude c916ed89b5 Add unit tests for pipeline layout, routing and SVG drawing 2026-10-11 22:28:16 +02:00
claude 5146111ad5 Add the pipeline flow layout and SVG drawing, with routing that avoids steps 2026-10-11 22:28:16 +02:00
claude 71b4803120 Pipelines: cancel a run, look up a workload's step, keep cancelled runs cancelled 2026-10-11 22:28:16 +02:00
claude 2b80f804af Add Django integration tests for the pipeline scheduler 2026-10-11 22:28:16 +02:00
claude 0df26588f9 Add unit tests for the pipeline graph core 2026-10-11 22:28:16 +02:00
claude d456f2fecf Wire the pipeline scheduler in: models, finish hooks, admin 2026-10-11 22:28:16 +02:00
claude 429b765657 Add pipeline engine and management commands (start_pipeline, advance_pipelines) 2026-10-11 22:28:16 +02:00
claude 248b11473b Add pipeline graph core: schema, validation and decision logic 2026-10-11 22:28:16 +02:00
claude d77f096932 Make the site discoverable as "RektBench" in search engines (#14) 2026-10-11 22:18:32 +02:00
claude 07935271cb Redesign site icon to match the theme (#13) 2026-10-11 21:59:44 +02:00
rektdie 0e39c20ef3 Merge pull request 'Spsa panel' (#12) from spsa-panel into master
Reviewed-on: #12
2026-10-11 21:31:09 +02:00
claude 22bb0b934d Tune page: live updates that keep the SPSA panel interactive
live.js already polled /tune/<id>, but patching the page in place would have
wiped the chart, reordered the parameter rows under their listeners, dropped
pinned lines and closed any fold the reader had opened.

- live.js: leave the chart, the parameter list and its empty notice alone, keep
  the 'open' attribute of folds, and fire a 'live:patched' event with the fresh
  page after every patch.
- spsa_chart.js: on that event, hand the new history to the existing chart
  (pinned lines and the inspected point stay), or build it if the first results
  have just arrived.
- spsa_panel.js: on that event, refresh the numbers, bars and limit markers of
  each row in place, and re-sort when sorted by movement without jumping the
  scroll position.
2026-10-11 20:43:21 +02:00
claude 0167e19057 Tune page: collapsible Results by Machine, padding inside the progress panel and below Modify
- Results by Machine is a fold on Tune pages, closed by default, like the other
  secondary sections.
- .card has no padding of its own, so the content of the Tuning progress panel
  ran up to the border. It now keeps 16px clear on both sides and at the bottom.
- The Actions card ended on the Modify button with 4px below it; it now has 16px.
2026-10-11 20:42:25 +02:00
claude efc0a42f8b Tune page: keep the SPSA parameter list to a bounded, scrollable height
The list used to grow with the number of parameters and pushed the results
table far down the page. It now scrolls inside the panel, with the filter and
sort bar staying in view, and jumps back to the top when the order or filter
changes.
2026-10-11 20:35:16 +02:00
claude 87886c5771 Revert "Tune page: chart and parameter list side by side, every secondary section collapsed"
This reverts commit 7269fd96e9. Restores workload.html and spsa_chart.css to the state of de5ec59.
2026-10-11 20:34:13 +02:00
claude 7269fd96e9 Tune page: chart and parameter list side by side, every secondary section collapsed
The progress summary, the movement chart and a scrollable parameter list now
share one panel. Settings, Actions, Parameter details and Contributors are
single-line folds, closed by default, so the page fits on roughly one screen.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01TyAt5S5MAwLBY2idan1SwU
2026-10-11 18:52:04 +02:00
claude de5ec59ece Tune page: parameter history chart, two-column layout, collapsed settings
Record every SPSA parameter value as results arrive (media/spsa_history/<id>.json,
same idea as the LLR history). The Tune page plots how far each parameter has
moved from its start, as a share of its allowed range. Hovering or pinning a
parameter name follows its line. The page is now a main column (progress,
history, results, details) plus a side column (actions, settings), and the
settings and parameter details start collapsed.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01TyAt5S5MAwLBY2idan1SwU
2026-10-11 18:43:54 +02:00
claude 9aa7678b62 Tune page: visual SPSA parameter panel
Each parameter gets a range track (min to max) with its start tick, current
value and the drift between them. The panel header shows iteration progress.
Parameters can be filtered by name and sorted by how far they moved. The old
table stays below as "Parameter details".

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01TyAt5S5MAwLBY2idan1SwU
2026-10-11 18:37:35 +02:00
claude 4fffbf50b4 Merge pull request 'Design refresh: new theme, Ctrl+K quick search, live updates' (#11) from design-refresh into master 2026-10-11 17:52:35 +02:00
claude d5cea13fd6 Live updates: keep the LLR history graph current 2026-10-11 17:49:31 +02:00
claude deb68caa64 LLR history: redraw in place when newer data arrives 2026-10-11 17:49:25 +02:00
claude 6a024f3e5a Live updates: load live.css and live.js 2026-10-11 17:39:54 +02:00
claude 9aa9a2b447 Live updates: styles 2026-10-11 17:39:50 +02:00
claude c367dd761a Live updates: pages refresh themselves in place 2026-10-11 17:39:43 +02:00
claude 05275645f5 Quick search: build workload urls in the view 2026-10-11 17:29:32 +02:00
claude 5793204b1b Quick search: Ctrl+K palette, live test endpoint and wiring 2026-10-11 17:29:20 +02:00
claude 26a0394ca9 Quick search: palette behaviour 2026-10-11 17:28:50 +02:00
claude d2827ee8f3 Quick search: fix font fallbacks 2026-10-11 17:28:19 +02:00
claude 963ba2151e Quick search: palette styles 2026-10-11 17:28:10 +02:00
claude 977ac2e4f9 Quick search: drop the Discord entry 2026-10-11 17:27:52 +02:00
claude 0b8862cc2c Quick search: palette markup partial 2026-10-11 12:56:01 +02:00
claude cbf4e59672 Index: drop the Awaiting artifacts counter card 2026-10-11 12:47:06 +02:00
claude 0dab31718a Restore result cell styling (outline, hatching, clearer blue) 2026-10-11 12:27:50 +02:00
claude 142296006b Workload page: revert hero, Dev/Base table, action hiding and confirms; keep full author names and server-rendered timestamps 2026-10-11 12:26:12 +02:00
claude 54538edcb1 Test list: drop state class from result cell 2026-10-11 12:25:23 +02:00
claude 44d6bfe7e8 Remove result cell restyling (outline, hatching, blue); keep full author names 2026-10-11 12:25:18 +02:00
claude e67bdfaa03 Workload page: load uitags so test_status and progress_info resolve (fixes 500) 2026-10-11 12:23:03 +02:00
claude e16b2e0b60 Workload config as Dev/Base comparison, full author names, server-rendered <time> stamps
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01TyAt5S5MAwLBY2idan1SwU
2026-10-11 11:59:25 +02:00
claude 236d69cfb8 Workload page: result hero, hide unavailable actions, confirm destructive ones
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01TyAt5S5MAwLBY2idan1SwU
2026-10-11 11:55:32 +02:00
claude 7718d593f4 Result cells: outline for tests without a verdict, diagonal hatching for stopped tests, clearer blue 2026-10-11 01:41:03 +02:00
claude dfa7687247 Design refresh: warm graphite palette, green accent, sentence-case labels, LLR gauge for SPRT tests 2026-10-11 01:33:55 +02:00
32 changed files with 5630 additions and 198 deletions

No files matched your search

+227
View File
@@ -0,0 +1,227 @@
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
# #
# OpenBench is a chess engine testing framework authored by Andrew Grant. #
# <https://github.com/AndyGrant/OpenBench> <andrew@grantnet.us> #
# #
# OpenBench is free software: you can redistribute it and/or modify #
# it under the terms of the GNU General Public License as published by #
# the Free Software Foundation, either version 3 of the License, or #
# (at your option) any later version. #
# #
# OpenBench is distributed in the hope that it will be useful, #
# but WITHOUT ANY WARRANTY; without even the implied warranty of #
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the #
# GNU General Public License for more details. #
# #
# You should have received a copy of the GNU General Public License #
# along with this program. If not, see <http://www.gnu.org/licenses/>. #
# #
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
# The settings of a pipeline step, filled in the way that the Create Test page
# fills them in ( see create_workload.js ): the engine, its repository and its
# default network, then the "default" preset of the engine, then the preset that
# was asked for, where a "both_" setting goes to the dev and the base alike.
# That is what lets a pipeline ask for one thing only, the dev branch, just like
# a single test does.
#
# Pure Python, like the graph module: no Django, no database. Everything that
# comes from the server is handed in, so that all of it can be tested on its own
# ( see UnitTests/test_pipeline_defaults.py ).
import re
from OpenBench.pipeline_graph import ALLOWED_FIELDS, CONDITIONAL_FIELDS, REQUIRED_FIELDS
from OpenBench.pipeline_graph import DEFAULT_MAX_STEPS, DEFAULT_MAX_VISITS, SCHEMA_VERSION
# What the Create Test page starts out with, before any preset is applied
FORM_DEFAULTS = {
'upload_pgns' : 'FALSE', 'priority' : '0', 'throughput' : '1000',
'syzygy_wdl' : 'DISABLED', 'syzygy_adj' : 'OPTIONAL',
}
# Only for engines whose presets say nothing about them, instead of a blank that can never run
FALLBACKS = {
'workload_size' : '32',
'win_adj' : 'movecount=3 score=400',
'draw_adj' : 'movenumber=40 movecount=8 score=10',
}
# Required settings that are allowed to be empty: "no network"
BLANK_OK = ('dev_network', 'base_network')
# One word, no spaces or quotes. Whether it exists is for Github to say, later
BRANCH_PATTERN = re.compile(r'[^\s"\'\\\x00-\x1f\x7f]{1,255}')
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
# PRESETS #
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
def preset_names(engine_config):
""" The test presets of an engine, in the order that its config lists them """
return [name for name in (engine_config.get('test_presets') or {}) if name != 'default']
def _expand(settings):
""" ( key, value ) pairs, with both_x turned into dev_x and base_x """
pairs = []
for key, value in settings.items():
if key.startswith('both_'):
pairs.append(('dev_' + key[len('both_'):], value))
pairs.append(('base_' + key[len('both_'):], value))
else:
pairs.append((key, value))
return pairs
def preset_settings(engine_config, preset):
""" What choosing a preset sets, in the order that the page applies it """
presets = engine_config.get('test_presets') or {}
pairs = _expand(presets.get('default') or {})
if preset != 'default':
pairs += _expand(presets.get(preset) or {})
return pairs
def time_control(engine_config, preset):
return str(dict(preset_settings(engine_config, preset)).get('dev_time_control', ''))
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
# NETWORKS #
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
def default_network(networks, engine):
""" The network that the page has selected for an engine: the last one flagged default """
chosen = ''
for network in networks:
if network.get('engine') == engine and network.get('default'):
chosen = network.get('sha256') or ''
return chosen
def find_network(networks, engine, wanted):
""" A preset may name a network, or give its hash. None when it is neither """
wanted = str(wanted)
if wanted in ('', 'None'):
return ''
found = None
for network in networks:
if network.get('engine') == engine and wanted in (network.get('name'), network.get('sha256')):
found = network.get('sha256') or ''
return found
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
# PAYLOAD #
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
def clean_branch(text):
""" The branch, or None if it cannot be one """
text = (text or '').strip()
return text if BRANCH_PATTERN.fullmatch(text) else None
def test_payload(engine, engine_config, preset, dev_branch, repos=None, networks=(), books=(), base_branch=''):
""" Returns ( payload, missing ): every setting of a Test step, as the Create
Test page would have it, and the names of the settings that nothing
could fill in. The payload may only be used when nothing is missing. """
repo = (repos or {}).get(engine) or engine_config.get('source') or ''
network = default_network(networks, engine)
payload = dict(FORM_DEFAULTS)
payload.update({
'dev_engine' : engine, 'base_engine' : engine,
'dev_repo' : repo, 'base_repo' : repo,
'dev_network' : network, 'base_network' : network,
})
mode = 'SPRT'
for key, value in preset_settings(engine_config, preset):
if key in ('dev_network', 'base_network'):
value = find_network(networks, engine, value)
if value is None: continue # Not one that exists. The page keeps what it had
# Like the page: the last of these that a preset sets decides the mode
if key == 'test_max_games': mode = 'GAMES'
if key in ('test_bounds', 'test_confidence'): mode = 'SPRT'
payload[key] = str(value)
for key, value in FALLBACKS.items():
if not str(payload.get(key, '')).strip():
payload[key] = value
if not str(payload.get('book_name', '')).strip():
payload['book_name'] = next(iter(books), '')
payload['test_mode'] = mode
payload['dev_branch'] = dev_branch
if base_branch:
payload['base_branch'] = base_branch
unused = ('test_max_games',) if mode == 'SPRT' else ('test_bounds', 'test_confidence')
payload = { key : value for key, value in payload.items() if key in ALLOWED_FIELDS and key not in unused }
required = REQUIRED_FIELDS['TEST'] + CONDITIONAL_FIELDS[mode]
missing = [key for key in required if key not in BLANK_OK and not str(payload.get(key, '')).strip()]
return payload, missing
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
# GRAPH #
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
def quick_graph(steps):
""" steps is [ ( name, payload ) ]. Each one starts when the one before it
passed. If anything else happens, the pipeline simply ends. """
graph = {
'version' : SCHEMA_VERSION, 'start' : 'step1',
'max_visits' : DEFAULT_MAX_VISITS, 'max_steps' : DEFAULT_MAX_STEPS,
'steps' : {}, 'edges' : [],
}
seen = {}
for index, (name, payload) in enumerate(steps, 1):
key = 'step%d' % (index)
seen[name] = seen.get(name, 0) + 1
label = name if seen[name] == 1 else '%s (%d)' % (name, seen[name])
graph['steps'][key] = { 'name' : label[:64], 'kind' : 'TEST', 'payload' : payload }
if index > 1:
graph['edges'].append({ 'from' : 'step%d' % (index - 1), 'on' : 'passed', 'to' : key })
return graph
def quick_name(dev_branch, names):
return ('%s: %s' % (dev_branch, ' then '.join(names)))[:128]
+409 -1
View File
@@ -30,14 +30,20 @@
# of, and takes no input from the request at all except which object it is for.
# Every decision, allowed or refused, leaves an event behind.
import OpenBench.config
import OpenBench.pipeline_defaults as defaults
import OpenBench.pipeline_graph as graphs
import OpenBench.pipeline_layout as drawing
import OpenBench.pipelines
import OpenBench.views
import copy
import json
from django.http import JsonResponse
from django.views.decorators.http import require_POST
from OpenBench.models import LogEvent, Pipeline, PipelineRun, Profile, StepRun, Test
from OpenBench.models import LogEvent, Network, Pipeline, PipelineRun, Profile, StepRun, Test
STATUS_LABELS = {
'QUEUED' : 'Waiting', 'LAUNCHING' : 'Starting', 'RUNNING' : 'Running',
@@ -381,3 +387,405 @@ def pipeline_run_cancel(request, run_id):
return OpenBench.views.redirect(request, '/pipelines/run/%d/' % (run.id), error='This run is already over')
return OpenBench.views.redirect(request, '/pipelines/run/%d/' % (run.id), status='Run cancelled')
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
# EDITING #
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
# Anybody with an enabled account may make a Pipeline, just like they may make a
# Test. Changing one later is the same can_manage() rule as everything else.
# The editor page builds the graph in the browser. Whatever it sends is never
# trusted: it is validated here by exactly the code that validates a run.
MAX_GRAPH_BYTES = 262144
_GENERAL_DEFAULTS = {
'upload_pgns' : 'FALSE', 'priority' : '0', 'throughput' : '1000',
'syzygy_wdl' : 'OPTIONAL', 'syzygy_adj' : 'OPTIONAL',
'win_adj' : 'movecount=3 score=400',
'draw_adj' : 'movenumber=40 movecount=8 score=10',
}
PAYLOAD_DEFAULTS = {
'TEST' : dict(_GENERAL_DEFAULTS, workload_size='32', test_mode='SPRT', test_bounds='[0.00, 3.00]', test_confidence='[0.05, 0.05]'),
'TUNE' : dict(_GENERAL_DEFAULTS),
'DATAGEN' : dict(_GENERAL_DEFAULTS, workload_size='32'),
}
def _blank_graph():
return {
'version' : graphs.SCHEMA_VERSION,
'start' : 'step1',
'max_visits' : graphs.DEFAULT_MAX_VISITS,
'max_steps' : graphs.DEFAULT_MAX_STEPS,
'steps' : { 'step1' : { 'name' : 'Step 1', 'kind' : 'TEST', 'payload' : dict(PAYLOAD_DEFAULTS['TEST']) } },
'edges' : [],
}
def _parse_graph(raw):
if not isinstance(raw, str) or len(raw) > MAX_GRAPH_BYTES:
return None
try: graph = json.loads(raw)
except ValueError: return None
return graph if isinstance(graph, dict) else None
def _tidy(graph):
keys = ('version', 'start', 'max_visits', 'max_steps', 'steps', 'edges')
return { key : graph[key] for key in keys if key in graph }
def _check(graph):
# validate_graph() is built for garbage, but a page that talks to the browser
# should never answer with a 500 because of what the browser sent
try: return graphs.validate_graph(graph)
except Exception: return [graphs.issue('error', 'graph.invalid', 'The pipeline is not valid')]
def _named(issues, graph):
steps = graph.get('steps') if isinstance(graph, dict) else None
steps = steps if isinstance(steps, dict) else {}
named = []
for entry in issues:
step = steps.get(entry['step']) if isinstance(entry['step'], str) else None
name = step.get('name') if isinstance(step, dict) else None
named.append(dict(entry, name=name or entry['step']))
return named
def _editor(request, pipeline, name, graph, issues=None, error=None):
data = {
'pipeline' : pipeline,
'name' : name,
'graph' : graph,
'issues' : _named(issues or [], graph),
'meta' : {
'kinds' : list(graphs.KINDS),
'outcomes' : list(graphs.EDGE_CONDITIONS),
'required' : graphs.REQUIRED_FIELDS,
'conditional' : graphs.CONDITIONAL_FIELDS,
'allowed' : sorted(graphs.ALLOWED_FIELDS),
'defaults' : PAYLOAD_DEFAULTS,
'limits' : { 'steps' : graphs.LIMIT_STEPS, 'visits' : graphs.LIMIT_MAX_VISITS, 'total' : graphs.LIMIT_MAX_STEPS },
},
}
return OpenBench.views.render(request, 'pipeline_edit.html', data, error=error)
def _submit(request, profile, found):
""" Shared by creating and editing. Saves, or shows the editor again with what was wrong """
name = (request.POST.get('name') or '').strip()
graph = _parse_graph(request.POST.get('graph'))
errors = []
if not (1 <= len(name) <= 128):
errors.append('Give the pipeline a name of up to 128 characters')
if graph is None:
errors.append('The pipeline could not be read. Reload the page and try again')
return _editor(request, found, name, _blank_graph(), error='\n'.join(errors))
issues = _check(graph)
if graphs.has_errors(issues):
errors.append('The pipeline has problems, see the checks below')
if errors:
return _editor(request, found, name, graph, issues, error='\n'.join(errors))
graph = _tidy(graph)
if found is None:
found = Pipeline.objects.create(name=name, author=profile.user.username, graph=graph)
action = 'CREATED'
else:
found.name = name
found.graph = graph
found.save()
action = 'EDITED'
_audit(profile.user.username, 'PIPELINE #%d %s' % (found.id, action))
return OpenBench.views.redirect(request, '/pipelines/%d/' % (found.id), status='Pipeline saved')
def pipeline_new(request):
profile = viewer(request)
if profile is None:
return _turn_away(request, profile)
if request.method != 'POST':
return _editor(request, None, '', _blank_graph())
return _submit(request, profile, None)
def pipeline_edit(request, id):
profile = viewer(request)
if profile is None:
return _turn_away(request, profile)
found = Pipeline.objects.filter(id=id, deleted=False).first()
if found is None:
return _missing(request)
if not can_manage(profile, found):
return _turn_away(request, profile, id, 'edit')
# Runs that are going work from a snapshot of the graph, so this is safe at any time
if request.method != 'POST':
return _editor(request, found, found.name, copy.deepcopy(found.graph))
return _submit(request, profile, found)
@require_POST
def pipeline_check(request):
""" Validates a graph without saving it, for the Check button of the editor """
if viewer(request) is None:
return JsonResponse({ 'error' : 'Not allowed' }, status=403)
graph = _parse_graph(request.POST.get('graph'))
if graph is None:
return JsonResponse({ 'issues' : [graphs.issue('error', 'graph.invalid', 'The pipeline could not be read')] })
return JsonResponse({ 'issues' : _check(graph) })
MAX_PREVIEW_EDGES = 400
def _drawable(graph):
""" Whether a graph is sound enough in shape to be laid out. Whatever else is
wrong with it, the editor still wants to see it, so that it can be fixed """
steps, edges = graph.get('steps'), graph.get('edges', [])
return (
isinstance(steps, dict) and 0 < len(steps) <= graphs.LIMIT_STEPS
and all(isinstance(step, dict) for step in steps.values())
and isinstance(edges, list) and len(edges) <= MAX_PREVIEW_EDGES
and all(isinstance(edge, dict) for edge in edges)
)
@require_POST
def pipeline_preview(request):
""" The flow of a graph as it is drawn on a run, and its checks, for the
editor to show while a pipeline is being built. Saves nothing """
if viewer(request) is None:
return JsonResponse({ 'error' : 'Not allowed' }, status=403)
graph = _parse_graph(request.POST.get('graph'))
if graph is None:
return JsonResponse({ 'svg' : '', 'issues' : [graphs.issue('error', 'graph.invalid', 'The pipeline could not be read')] })
svg = ''
if _drawable(graph):
try: svg = drawing.render_svg(graph)
except Exception: svg = '' # A half built graph is not a reason for a 500
return JsonResponse({ 'svg' : svg, 'issues' : _named(_check(graph), graph) })
def pipeline_test_fields(request, test_id):
""" The settings of an existing SPRT or Games test, as the settings of a step """
if viewer(request) is None:
return JsonResponse({ 'error' : 'Not allowed' }, status=403)
test = Test.objects.select_related('dev', 'base').filter(id=test_id).first()
if test is None or test.test_mode not in ('SPRT', 'GAMES'):
return JsonResponse({ 'error' : 'There is no SPRT or Games test with that number' }, status=404)
fields = {
'dev_engine' : test.dev_engine, 'base_engine' : test.base_engine,
'dev_repo' : test.dev_repo, 'base_repo' : test.base_repo,
'dev_branch' : test.dev.name, 'base_branch' : test.base.name,
'dev_network' : test.dev_network, 'base_network' : test.base_network,
'dev_options' : test.dev_options, 'base_options' : test.base_options,
'dev_time_control' : test.dev_time_control, 'base_time_control' : test.base_time_control,
'book_name' : test.book_name, 'upload_pgns' : test.upload_pgns,
'priority' : test.priority, 'throughput' : test.throughput,
'workload_size' : test.workload_size, 'test_mode' : test.test_mode,
'syzygy_wdl' : test.syzygy_wdl, 'syzygy_adj' : test.syzygy_adj,
'win_adj' : test.win_adj, 'draw_adj' : test.draw_adj,
}
if test.test_mode == 'SPRT':
fields['test_bounds'] = '[%.2f, %.2f]' % (test.elolower, test.eloupper)
fields['test_confidence'] = '[%.2f, %.2f]' % (test.beta, test.alpha)
else:
fields['test_max_games'] = test.max_games
return JsonResponse({ 'payload' : { key : str(value) for key, value in fields.items() } })
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
# QUICK START #
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
# What the New pipeline button opens. It asks for one thing, the dev branch, and
# fills in everything else the way that the Create Test page does ( the same
# presets, the same defaults, see pipeline_defaults.py ), so that a branch and an
# Enter are all that it takes, as they are for a single test. What comes out is a
# plain pipeline, which the editor can change like any other.
def _quick_engine(profile, wanted):
""" The engine to make tests for: the one asked for, else the default of this
person, else the first there is. '' when the server has none at all """
engines = OpenBench.config.OPENBENCH_CONFIG['engines']
for name in (wanted, profile.engine):
if name in engines:
return name
return next(iter(engines), '')
def _quick_choices(engine_config):
""" ( the presets to choose from, the one that goes first, the one that follows ) """
names = defaults.preset_names(engine_config)
first = 'STC' if 'STC' in names else (names[0] if names else '')
then = 'LTC' if 'LTC' in names and first != 'LTC' else ''
choices = [{ 'name' : name, 'time' : defaults.time_control(engine_config, name) } for name in names]
return choices, first, then
def _quick_page(request, engine, choices, form, error=None):
config = OpenBench.config.OPENBENCH_CONFIG
# What the presets say about the base branch, to show where the box is left blank
base = defaults.test_payload(engine, config['engines'][engine], form['first'], 'dev')[0].get('base_branch', '')
data = {
'engine' : engine,
'engines' : list(config['engines']),
'choices' : choices,
'form' : form,
'base' : base,
'more' : bool(form['base_branch'] or form['name'] or not base),
}
return OpenBench.views.render(request, 'pipeline_quick.html', data, error=error)
def pipeline_quick(request):
profile = viewer(request)
if profile is None:
return _turn_away(request, profile)
config = OpenBench.config.OPENBENCH_CONFIG
source = request.POST if request.method == 'POST' else request.GET
engine = _quick_engine(profile, source.get('engine'))
if not engine:
return OpenBench.views.redirect(request, '/pipelines/', error='No engine is set up on this server')
engine_config = config['engines'][engine]
choices, first, then = _quick_choices(engine_config)
names = [choice['name'] for choice in choices]
if not names:
return OpenBench.views.redirect(request, '/pipelines/new/', error='%s has no test presets, so its pipelines are made here' % (engine))
asked = {
'dev_branch' : (source.get('dev_branch' ) or '').strip(),
'base_branch' : (source.get('base_branch') or '').strip(),
'name' : (source.get('name' ) or '').strip(),
'first' : source.get('first', first),
'then' : source.get('then' , then ),
}
form = dict(asked,
first = asked['first'] if asked['first'] in names else first,
then = asked['then' ] if asked['then' ] in names else '')
if request.method != 'POST':
return _quick_page(request, engine, choices, form)
errors = []
branch = defaults.clean_branch(asked['dev_branch'])
if not asked['dev_branch']:
errors.append('Type the name of the branch to test')
elif branch is None:
errors.append('"%s" cannot be a branch, which has no spaces or quotes' % (asked['dev_branch'][:40]))
base = asked['base_branch']
if base and defaults.clean_branch(base) is None:
errors.append('"%s" cannot be a branch, which has no spaces or quotes' % (base[:40]))
if asked['first'] not in names:
errors.append('Pick the test to run first')
if asked['then'] and asked['then'] not in names:
errors.append('Pick the test to run after it, or none')
if errors:
return _quick_page(request, engine, choices, form, error='\n'.join(errors))
networks = list(Network.objects.all().values())
books = list(config['books'])
plan = [asked['first']] + ([asked['then']] if asked['then'] else [])
steps, lacking = [], []
for preset in plan:
payload, absent = defaults.test_payload(engine, engine_config, preset, branch, profile.repos, networks, books, base)
steps.append((preset, payload))
lacking += [(preset, key) for key in absent]
if any(key == 'base_branch' for _, key in lacking):
errors.append('Type the base branch, as the engine does not say which one to test against')
others = ['%s (%s)' % (key.replace('_', ' '), preset) for preset, key in lacking if key != 'base_branch']
if others:
errors.append('The presets of %s leave out: %s\nFill those in with the editor' % (engine, ', '.join(others)))
if errors:
return _quick_page(request, engine, choices, form, error='\n'.join(errors))
graph = defaults.quick_graph(steps)
issues = _check(graph)
if graphs.has_errors(issues): # Nothing for a person to fix: this page never builds anything that is wrong
problems = '\n'.join(i['message'] for i in issues if i['level'] == 'error')
return _quick_page(request, engine, choices, form, error='The pipeline could not be made:\n' + problems)
author = profile.user.username
title = asked['name'][:128] or defaults.quick_name(branch, [label for label, _ in steps])
pipeline = Pipeline.objects.create(name=title, author=author, graph=_tidy(graph))
pipeline_id = pipeline.id
_audit(author, 'PIPELINE #%d CREATED' % (pipeline_id))
if request.POST.get('action') == 'save':
return OpenBench.views.redirect(request, '/pipelines/%d/' % (pipeline_id), status='Pipeline saved')
run, issues = OpenBench.pipelines.start_pipeline(pipeline, starter=author)
first_step = StepRun.objects.filter(run=run).order_by('id').first() if run else None
if run is None or (run.status == 'ERROR' and first_step):
reason = first_step.message if first_step else '\n'.join(i['message'] for i in issues if i['level'] == 'error')
# Nothing was made, and a pipeline that never made anything is of no use to anybody
pipeline.delete()
_audit(author, 'PIPELINE #%d DISCARDED' % (pipeline_id))
return _quick_page(request, engine, choices, form, error='The first test could not be created:\n' + reason)
return OpenBench.views.redirect(request, '/pipelines/run/%d/' % (run.id), status='Pipeline started')
+50
View File
@@ -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')
+68
View File
@@ -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; }
}
+325
View File
@@ -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();
})();
+52 -1
View File
@@ -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
View File
@@ -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

+286
View File
@@ -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; }
}
+462
View File
@@ -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';
});
})();
+290
View File
@@ -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;
}
+286
View File
@@ -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; }
}
+511
View File
@@ -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();
})();
+225
View File
@@ -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; }
}
+110
View File
@@ -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();
})();
+134
View File
@@ -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)
+21 -1
View File
@@ -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)
+544 -2
View File
@@ -24,15 +24,21 @@
# The Pipeline pages, with a real ( test ) database and the real URL routing. As
# in tests_pipelines.py, only the call out to Github is replaced.
import copy
import json
import re
from html.parser import HTMLParser
from unittest import mock
from django.contrib.auth.models import User
from django.test import Client
import OpenBench.config
import OpenBench.pipelines as pipelines
import OpenBench.tests_pipelines as base
from OpenBench.models import LogEvent, Pipeline, PipelineRun, Profile, StepRun, Test
from OpenBench.models import LogEvent, Network, Pipeline, PipelineRun, Profile, StepRun, Test
def make_user(name, enabled=True, approver=False):
user = User.objects.create_user(name, '%s@example.com' % (name), 'pw')
@@ -53,7 +59,10 @@ class PagesTestCase(base.PipelineTestCase):
self.dave = make_user('dave', enabled=False) # A disabled account
def client_for(self, user=None, **kwargs):
client = Client(**kwargs)
# The site sends everything to https, as it is behind a proxy that says that it was. So do the tests
client = Client(HTTP_X_FORWARDED_PROTO='https', **kwargs)
if user is not None: client.force_login(user)
return client
@@ -493,3 +502,536 @@ class ChipTests(PagesTestCase):
page = self.client_for(self.user).get(url).content.decode()
self.assertNotIn('<script>alert(1)', page)
class PreviewTests(PagesTestCase):
""" The flow and the checks of a pipeline that is still being built, drawn by the server """
def drawing(self, edges=None, name='Alpha'):
return {
'version' : 1, 'start' : 'a', 'edges' : edges or [],
'steps' : {
'a' : { 'name' : name, 'kind' : 'TEST', 'payload' : {} },
'b' : { 'name' : 'Beta', 'kind' : 'TEST', 'payload' : {} },
},
}
def preview(self, graph, user=None, **kwargs):
raw = graph if isinstance(graph, str) else json.dumps(graph)
return self.client_for(user, **kwargs).post('/pipelines/preview/', { 'graph' : raw })
def test_a_graph_is_drawn_with_something_to_click_on(self):
data = self.preview(self.drawing([{ 'from' : 'a', 'on' : 'passed', 'to' : 'b' }]), self.user).json()
self.assertIn('class="pl-graph"', data['svg'])
self.assertIn('data-step="a"', data['svg'])
self.assertIn('data-step="b"', data['svg'])
self.assertIn('data-edge="0"', data['svg'])
def test_a_graph_that_is_still_being_built_is_drawn_and_its_problems_are_named(self):
data = self.preview(self.drawing(), self.user).json()
missing = [issue for issue in data['issues'] if issue['code'] == 'payload.missing']
self.assertIn('data-step="a"', data['svg'])
self.assertEqual(sorted(issue['name'] for issue in missing), ['Alpha', 'Beta'])
def test_nothing_is_saved(self):
before = Pipeline.objects.count()
self.preview(self.drawing(), self.user)
self.assertEqual(Pipeline.objects.count(), before)
def test_only_enabled_accounts_may_ask(self):
for user, status in ((None, 403), (self.dave, 403), (self.bob, 200)):
self.assertEqual(self.preview(self.drawing(), user).status_code, status)
def test_it_needs_the_csrf_token_and_a_post(self):
self.assertEqual(self.preview(self.drawing(), self.user, enforce_csrf_checks=True).status_code, 403)
self.assertEqual(self.client_for(self.user).get('/pipelines/preview/').status_code, 405)
def test_garbage_is_reported_and_is_not_a_crash(self):
for raw in ('nope', '[]', '{"steps": {"x": "not a step"}}',
'{"version": 1, "steps": {"x": {"kind": "TEST", "payload": []}}, "edges": [5]}'):
response = self.preview(raw, self.user)
data = response.json()
self.assertEqual(response.status_code, 200, raw)
self.assertEqual(data['svg'], '', raw)
self.assertTrue(any(issue['level'] == 'error' for issue in data['issues']), raw)
def test_a_graph_too_big_to_be_real_is_not_drawn(self):
steps = { 's%d' % i : { 'name' : 'S', 'kind' : 'TEST', 'payload' : {} } for i in range(31) }
data = self.preview({ 'version' : 1, 'start' : 's0', 'steps' : steps, 'edges' : [] }, self.user).json()
self.assertEqual(data['svg'], '')
def test_names_cannot_inject_markup(self):
data = self.preview(self.drawing(name='<script>alert(1)</script>'), self.user).json()
self.assertIn('class="pl-graph"', data['svg'])
self.assertNotIn('<script>', data['svg'])
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
# QUICK START #
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
# An engine as Engines/*.json has it, presets only. The page asks the config for
# these, so the tests do not depend on which engines a server happens to have
QUICK_ENGINE = {
'source' : 'https://github.com/o/Engine',
'test_presets' : {
'default' : {
'base_branch' : 'main', 'book_name' : 'UHO.epd',
'test_bounds' : '[0.00, 5.00]', 'test_confidence' : '[0.05, 0.05]',
'win_adj' : 'movecount=3 score=400', 'draw_adj' : 'movenumber=40 movecount=8 score=10',
},
'STC' : { 'both_options' : 'Threads=1 Hash=8', 'both_time_control' : '8.0+0.08', 'workload_size' : 32 },
'LTC' : { 'both_options' : 'Threads=1 Hash=64', 'both_time_control' : '40.0+0.4', 'workload_size' : 8 },
},
}
class QuickForm(HTMLParser):
""" The quick page as a browser makes of it: its fields, and what they hold. The
site minifies its pages, so the markup itself is nothing to compare with """
def __init__(self, page):
super().__init__()
self.inside, self.inputs, self.selects, self.attrs, self.buttons, self.details = False, {}, {}, {}, [], []
self._select, self._option = None, None
self.feed(page)
def handle_starttag(self, tag, attrs):
attrs = dict(attrs)
if tag == 'form' and attrs.get('action') == '/pipelines/quick/':
self.inside = True
if not self.inside:
return
if tag == 'input':
self.inputs[attrs.get('name')] = attrs
elif tag == 'select':
self._select = attrs.get('id')
self.selects[self._select], self.attrs[self._select] = [], attrs
elif tag == 'option':
self._option = [attrs.get('value'), 'selected' in attrs, '']
self.selects[self._select].append(self._option)
elif tag == 'button':
self.buttons.append(attrs)
elif tag == 'details':
self.details.append(attrs)
def handle_endtag(self, tag):
if tag == 'form' : self.inside = False
if tag == 'option': self._option = None
if tag == 'select': self._select = None
def handle_data(self, data):
if self._option is not None: self._option[2] += data
def chosen(self, select):
""" ( value, text ) of what a select has chosen """
return next((value, text) for value, selected, text in self.selects[select] if selected)
class QuickTests(PagesTestCase):
""" New pipeline: a branch, then Enter. The real scheduler and the real routing,
with the engines of the config swapped for the one above """
def setUp(self):
super().setUp()
patch = mock.patch.dict(OpenBench.config.OPENBENCH_CONFIG, engines={ 'Engine' : copy.deepcopy(QUICK_ENGINE) }, books={ 'UHO.epd' : {} })
patch.start(); self.addCleanup(patch.stop)
self.engines = OpenBench.config.OPENBENCH_CONFIG['engines']
def page(self, url='/pipelines/quick/'):
return self.client_for(self.user).get(url).content.decode()
def post(self, data, user=None, **kwargs):
return self.client_for(user or self.user, **kwargs).post('/pipelines/quick/', data)
def fields_of(self, pipeline, step='step1'):
return pipeline.graph['steps'][step]['payload']
# The page
def test_the_page_asks_for_a_branch_and_offers_the_presets(self):
page = self.page()
form = QuickForm(page)
self.assertIn('autofocus', form.inputs['dev_branch'])
self.assertIn('required', form.inputs['dev_branch'])
self.assertEqual(form.chosen('first'), ('STC', 'STC (8.0+0.08)'))
self.assertEqual(form.chosen('then'), ('LTC', 'Then LTC (40.0+0.4)'))
self.assertEqual([option[0] for option in form.selects['first']], ['STC', 'LTC'])
self.assertEqual((form.selects['then'][0][0], form.selects['then'][0][2]), ('', 'Stop there'))
self.assertEqual([option[0] for option in form.selects['then']], ['', 'STC', 'LTC'])
self.assertIn('href="/pipelines/new/"', page)
def test_the_first_button_in_the_form_is_the_one_that_enter_presses(self):
buttons = QuickForm(self.page()).buttons
self.assertEqual([(button['name'], button['value']) for button in buttons], [('action', 'run'), ('action', 'save')])
self.assertEqual([button['type'] for button in buttons], ['submit', 'submit'])
def test_the_base_branch_is_shown_as_what_it_would_be(self):
form = QuickForm(self.page())
self.assertEqual(form.inputs['base_branch']['placeholder'], 'main')
self.assertEqual(form.inputs['base_branch']['value'], '') # Blank: whatever the presets say
self.assertNotIn('required', form.inputs['base_branch'])
self.assertNotIn('open', form.details[0]) # Nothing in there needs doing
def test_a_single_engine_is_not_asked_about(self):
form = QuickForm(self.page())
self.assertEqual((form.inputs['engine']['type'], form.inputs['engine']['value']), ('hidden', 'Engine'))
self.assertNotIn('engine', form.selects)
def test_several_engines_can_be_switched_between_without_losing_the_branch(self):
self.engines['Second'] = copy.deepcopy(QUICK_ENGINE)
form = QuickForm(self.page())
self.assertEqual([option[0] for option in form.selects['engine']], ['Engine', 'Second'])
self.assertNotIn('engine', form.inputs)
self.assertIn("encodeURIComponent(document.getElementById('dev_branch').value)", form.attrs['engine']['onchange'])
self.assertIn('&dev_branch=', form.attrs['engine']['onchange'])
form = QuickForm(self.page('/pipelines/quick/?engine=Second&dev_branch=feature'))
self.assertEqual(form.chosen('engine'), ('Second', 'Second'))
self.assertEqual(form.inputs['dev_branch']['value'], 'feature')
def test_the_default_engine_of_the_person_is_the_one_shown(self):
self.engines['Second'] = copy.deepcopy(QUICK_ENGINE)
self.profile.engine = 'Second'; self.profile.save()
self.assertEqual(QuickForm(self.page()).chosen('engine'), ('Second', 'Second'))
def test_an_engine_with_one_preset_runs_just_that(self):
del self.engines['Engine']['test_presets']['LTC']
form = QuickForm(self.page())
self.assertEqual(form.chosen('first'), ('STC', 'STC (8.0+0.08)'))
self.assertEqual(form.chosen('then'), ('', 'Stop there'))
self.post({ 'dev_branch' : 'my-branch' })
pipeline = Pipeline.objects.get()
self.assertEqual((list(pipeline.graph['steps']), pipeline.graph['edges']), (['step1'], []))
self.assertEqual(pipeline.name, 'my-branch: STC')
def test_an_engine_without_an_stc_starts_with_the_first_preset_it_lists(self):
presets = self.engines['Engine']['test_presets']
self.engines['Engine']['test_presets'] = { 'default' : presets['default'], 'Fast' : presets['STC'], 'LTC' : presets['LTC'] }
form = QuickForm(self.page())
self.assertEqual(form.chosen('first')[0], 'Fast')
self.assertEqual(form.chosen('then')[0], 'LTC')
self.post({ 'dev_branch' : 'my-branch' })
self.assertEqual(Pipeline.objects.get().name, 'my-branch: Fast then LTC')
def test_an_engine_without_test_presets_sends_the_person_to_the_editor(self):
self.engines['Engine']['test_presets'] = { 'default' : {} }
response = self.client_for(self.user).get('/pipelines/quick/')
self.assertEqual((response.status_code, response['Location']), (302, '/pipelines/new/'))
def test_a_server_without_engines_says_so(self):
self.engines.clear()
response = self.client_for(self.user).get('/pipelines/quick/')
self.assertEqual((response.status_code, response['Location']), (302, '/pipelines/'))
def test_visitors_log_in_and_disabled_accounts_are_told(self):
anonymous = self.client_for().get('/pipelines/quick/')
disabled = self.client_for(self.dave).get('/pipelines/quick/')
self.assertEqual((anonymous.status_code, anonymous['Location']), (302, '/login/'))
self.assertEqual((disabled.status_code, disabled['Location']), (302, '/index/'))
def test_nobody_can_post_who_may_not_see(self):
self.assertEqual(self.post({ 'dev_branch' : 'x' }, self.dave)['Location'], '/index/')
self.assertEqual(self.client_for().post('/pipelines/quick/', { 'dev_branch' : 'x' })['Location'], '/login/')
self.assertEqual((Pipeline.objects.count(), len(self.creator.calls)), (0, 0))
def test_it_needs_the_csrf_token(self):
response = self.post({ 'dev_branch' : 'x' }, enforce_csrf_checks=True)
self.assertEqual(response.status_code, 403)
self.assertEqual(Pipeline.objects.count(), 0)
def test_the_list_offers_both_ways_to_make_one(self):
page = self.page('/pipelines/')
self.assertIn('href="/pipelines/quick/"', page)
self.assertIn('href="/pipelines/new/"', page)
# One branch, and Enter
def test_a_branch_is_all_it_takes(self):
response = self.post({ 'dev_branch' : 'my-branch' })
pipeline = Pipeline.objects.get()
run = PipelineRun.objects.get()
self.assertEqual(response['Location'], '/pipelines/run/%d/' % run.id)
self.assertEqual((pipeline.name, pipeline.author), ('my-branch: STC then LTC', 'alice'))
self.assertEqual(list(pipeline.graph['steps']), ['step1', 'step2'])
self.assertEqual(pipeline.graph['edges'], [{ 'from' : 'step1', 'on' : 'passed', 'to' : 'step2' }])
self.assertEqual(run.starter, 'alice')
self.assertEqual((StepRun.objects.get().status, Test.objects.count()), ('RUNNING', 1))
def test_what_a_browser_sends_when_enter_is_pressed(self):
response = self.post({ 'engine' : 'Engine', 'dev_branch' : 'my-branch', 'first' : 'STC', 'then' : 'LTC',
'base_branch' : '', 'name' : '', 'action' : 'run' })
self.assertIn('/pipelines/run/', response['Location'])
self.assertEqual(Pipeline.objects.get().name, 'my-branch: STC then LTC')
def test_it_makes_the_settings_that_create_test_would(self):
self.post({ 'dev_branch' : 'my-branch' })
pipeline = Pipeline.objects.get()
stc, ltc = self.fields_of(pipeline, 'step1'), self.fields_of(pipeline, 'step2')
self.assertEqual((stc['dev_branch'], stc['base_branch']), ('my-branch', 'main'))
self.assertEqual((stc['dev_time_control'], stc['base_time_control']), ('8.0+0.08', '8.0+0.08'))
self.assertEqual((ltc['dev_time_control'], ltc['dev_options']), ('40.0+0.4', 'Threads=1 Hash=64'))
self.assertEqual((stc['dev_engine'], stc['dev_repo']), ('Engine', 'https://github.com/o/Engine'))
self.assertEqual((stc['test_mode'], stc['test_bounds'], stc['workload_size']), ('SPRT', '[0.00, 5.00]', '32'))
self.assertEqual((stc['syzygy_wdl'], stc['priority'], stc['throughput']), ('DISABLED', '0', '1000'))
def test_the_repo_and_the_network_of_the_person_are_used(self):
self.profile.repos = { 'Engine' : 'https://github.com/alice/Engine' }; self.profile.save()
Network.objects.create(default=True, sha256='abcd1234', name='n.nn', engine='Engine', author='alice')
self.post({ 'dev_branch' : 'my-branch' })
stc = self.fields_of(Pipeline.objects.get())
self.assertEqual((stc['dev_repo'], stc['base_repo']), ('https://github.com/alice/Engine',) * 2)
self.assertEqual((stc['dev_network'], stc['base_network']), ('abcd1234',) * 2)
def test_stopping_after_the_first_test(self):
self.post({ 'dev_branch' : 'my-branch', 'first' : 'LTC', 'then' : '' })
pipeline = Pipeline.objects.get()
self.assertEqual((pipeline.name, list(pipeline.graph['steps']), pipeline.graph['edges']), ('my-branch: LTC', ['step1'], []))
def test_a_name_and_a_base_branch_can_be_given(self):
self.post({ 'dev_branch' : 'my-branch', 'name' : 'Nightly check', 'base_branch' : 'release' })
pipeline = Pipeline.objects.get()
self.assertEqual(pipeline.name, 'Nightly check')
self.assertEqual(self.fields_of(pipeline, 'step1')['base_branch'], 'release')
self.assertEqual(self.fields_of(pipeline, 'step2')['base_branch'], 'release')
def test_a_branch_with_padding_is_trimmed(self):
self.post({ 'dev_branch' : ' my-branch ' })
self.assertEqual(self.fields_of(Pipeline.objects.get())['dev_branch'], 'my-branch')
def test_saving_does_not_start_anything(self):
response = self.post({ 'dev_branch' : 'my-branch', 'action' : 'save' })
pipeline = Pipeline.objects.get()
self.assertEqual(response['Location'], '/pipelines/%d/' % pipeline.id)
self.assertEqual((PipelineRun.objects.count(), len(self.creator.calls)), (0, 0))
def test_what_happened_is_written_down(self):
self.post({ 'dev_branch' : 'my-branch', 'action' : 'save' })
pipeline = Pipeline.objects.get()
self.assertEqual(self.events(), [('alice', 'PIPELINE #%d CREATED' % pipeline.id)])
def test_the_first_test_is_made_with_what_the_page_filled_in(self):
self.post({ 'dev_branch' : 'my-branch' })
made = self.creator.calls[0].POST
self.assertEqual((made['dev_branch'], made['base_branch']), ('my-branch', 'main'))
self.assertEqual((made['dev_time_control'], made['dev_options']), ('8.0+0.08', 'Threads=1 Hash=8'))
self.assertEqual(len(self.creator.calls), 1) # Only the first, so far
def test_a_pass_starts_the_next_test_with_its_own_settings(self):
self.post({ 'dev_branch' : 'my-branch' })
run = PipelineRun.objects.get()
self.finish(self.steps(run)['step1'], passed=True)
self.assertEqual(self.keys(run), ['step1', 'step2'])
self.assertEqual(self.status(run), 'RUNNING')
self.assertEqual(self.creator.calls[1].POST['dev_time_control'], '40.0+0.4')
self.assertEqual(self.creator.calls[1].POST['dev_branch'], 'my-branch')
def test_anything_but_a_pass_ends_it(self):
self.post({ 'dev_branch' : 'my-branch' })
run = PipelineRun.objects.get()
self.finish(self.steps(run)['step1'], failed=True)
self.assertEqual(self.keys(run), ['step1'])
self.assertEqual(self.status(run), 'COMPLETED')
self.assertEqual(len(self.creator.calls), 1)
def test_what_is_made_here_opens_everywhere_else(self):
self.post({ 'dev_branch' : 'my-branch' })
pipeline, run = Pipeline.objects.get(), PipelineRun.objects.get()
client = self.client_for(self.user)
for url in ('/pipelines/', '/pipelines/%d/' % pipeline.id):
response = client.get(url)
self.assertEqual(response.status_code, 200, url)
self.assertIn('my-branch: STC then LTC', response.content.decode(), url)
for url in ('/pipelines/%d/edit/' % pipeline.id, '/pipelines/run/%d/' % run.id):
self.assertEqual(client.get(url).status_code, 200, url)
# What goes wrong
def test_no_branch_asks_for_one_and_makes_nothing(self):
response = self.post({ 'dev_branch' : ' ' })
self.assertEqual(response.status_code, 200)
self.assertIn('Type the name of the branch to test', response.content.decode())
self.assertEqual((Pipeline.objects.count(), PipelineRun.objects.count()), (0, 0))
def test_a_branch_that_cannot_be_one_is_refused_and_kept_on_the_page(self):
response = self.post({ 'dev_branch' : 'two words' })
page = response.content.decode()
self.assertEqual(response.status_code, 200)
self.assertIn('cannot be a branch', page)
self.assertEqual(QuickForm(page).inputs['dev_branch']['value'], 'two words')
self.assertEqual(Pipeline.objects.count(), 0)
def test_a_base_branch_that_cannot_be_one_is_refused(self):
response = self.post({ 'dev_branch' : 'ok', 'base_branch' : 'no good' })
page = response.content.decode()
self.assertIn('cannot be a branch', page)
self.assertIn('open', QuickForm(page).details[0]) # Where it was typed
self.assertEqual(Pipeline.objects.count(), 0)
def test_a_preset_that_does_not_exist_is_refused(self):
for data in ({ 'first' : 'NOPE' }, { 'then' : 'NOPE' }):
response = self.post(dict(data, dev_branch='ok'))
self.assertEqual(response.status_code, 200, data)
self.assertEqual(Pipeline.objects.count(), 0, data)
def test_a_first_test_that_could_not_be_made_is_reported_and_leaves_nothing_behind(self):
self.creator.errors = ['my-branch could not be found']
response = self.post({ 'dev_branch' : 'my-branch' })
page = response.content.decode()
self.assertEqual(response.status_code, 200)
self.assertIn('The first test could not be created', page)
self.assertIn('my-branch could not be found', page)
self.assertEqual(QuickForm(page).inputs['dev_branch']['value'], 'my-branch') # Typed once is enough
self.assertEqual((Pipeline.objects.count(), PipelineRun.objects.count(), StepRun.objects.count()), (0, 0, 0))
self.assertEqual(Test.objects.count(), 0)
events = self.events()
self.assertTrue(events[0][1].endswith('CREATED'))
self.assertTrue(events[-1][1].endswith('DISCARDED'))
def test_the_second_try_works(self):
self.creator.errors = ['my-branch could not be found']
self.post({ 'dev_branch' : 'my-branch' })
self.creator.errors = None
response = self.post({ 'dev_branch' : 'my-branch' })
self.assertIn('/pipelines/run/', response['Location'])
self.assertEqual((Pipeline.objects.count(), PipelineRun.objects.count()), (1, 1))
def test_presets_that_leave_things_out_are_named(self):
self.engines['Engine']['test_presets']['Bare'] = {}
response = self.post({ 'dev_branch' : 'ok', 'first' : 'Bare', 'then' : '' })
page = response.content.decode()
self.assertIn('leave out', page)
self.assertIn('dev time control (Bare)', page)
self.assertEqual(Pipeline.objects.count(), 0)
def test_an_engine_that_names_no_base_branch_asks_for_it(self):
del self.engines['Engine']['test_presets']['default']['base_branch']
form = QuickForm(self.page())
self.assertIn('open', form.details[0])
self.assertIn('required', form.inputs['base_branch'])
self.assertEqual(form.inputs['base_branch']['placeholder'], 'The branch to compare against')
refused = self.post({ 'dev_branch' : 'ok' })
self.assertIn('Type the base branch', refused.content.decode())
self.assertEqual(Pipeline.objects.count(), 0)
accepted = self.post({ 'dev_branch' : 'ok', 'base_branch' : 'trunk' })
self.assertIn('/pipelines/run/', accepted['Location'])
self.assertEqual(self.fields_of(Pipeline.objects.get())['base_branch'], 'trunk')
def test_nothing_typed_can_inject_markup(self):
self.creator.errors = ['<script>alert(1)</script> could not be found']
page = self.post({ 'dev_branch' : '<u>zzz</u>', 'name' : '<b>nn</b>' }).content.decode()
self.assertNotIn('<script>alert', page)
self.assertNotIn('<u>zzz</u>', page)
self.assertNotIn('<b>nn</b>', page)
self.assertIn('&lt;u&gt;zzz&lt;/u&gt;', page)
+12 -1
View File
@@ -18,10 +18,14 @@
# #
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
import django.urls, OpenBench.views, OpenBench.pipeline_views
import django.urls, OpenBench.views, OpenBench.pipeline_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),
@@ -44,6 +48,12 @@ urlpatterns = [
django.urls.path(r'pipelines/<int:id>/start/', OpenBench.pipeline_views.pipeline_start),
django.urls.path(r'pipelines/<int:id>/toggle/', OpenBench.pipeline_views.pipeline_toggle),
django.urls.path(r'pipelines/<int:id>/delete/', OpenBench.pipeline_views.pipeline_delete),
django.urls.path(r'pipelines/<int:id>/edit/', OpenBench.pipeline_views.pipeline_edit),
django.urls.path(r'pipelines/new/', OpenBench.pipeline_views.pipeline_new),
django.urls.path(r'pipelines/quick/', OpenBench.pipeline_views.pipeline_quick),
django.urls.path(r'pipelines/check/', OpenBench.pipeline_views.pipeline_check),
django.urls.path(r'pipelines/preview/', OpenBench.pipeline_views.pipeline_preview),
django.urls.path(r'pipelines/test-fields/<int:test_id>/', OpenBench.pipeline_views.pipeline_test_fields),
django.urls.path(r'pipelines/run/<int:run_id>/', OpenBench.pipeline_views.pipeline_run),
django.urls.path(r'pipelines/run/<int:run_id>/cancel/', OpenBench.pipeline_views.pipeline_run_cancel),
@@ -103,6 +113,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),
+63
View File
@@ -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)
@@ -581,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 }
@@ -631,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':
@@ -639,6 +696,12 @@ 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)
+35
View File
@@ -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')
-5
View File
@@ -27,7 +27,6 @@
import datetime
import OpenBench.config
import OpenBench.pipelines
import OpenBench.views
from django.utils import timezone
@@ -67,10 +66,6 @@ def view_workload(request, workload, workload_type):
if workload.test_mode == 'SPRT':
data['llr_history_endpoint'] = '/api/test/%d/llr-history/' % (workload.id)
# Say so, when a Pipeline made this Workload. Pipelines are for people who are logged in
if request.user.is_authenticated:
data['pipeline_step'] = OpenBench.pipelines.step_of(workload.id)
if workload.book_name in OpenBench.config.OPENBENCH_CONFIG['books']:
data['book_url'] = OpenBench.config.OPENBENCH_CONFIG['books'][workload.book_name]['source']
+82
View File
@@ -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>&uarr;</kbd><kbd>&darr;</kbd>move</span>
<span><kbd>&crarr;</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="&gt;=">
<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>
+9 -3
View File
@@ -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>
+28 -6
View File
@@ -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>
@@ -223,5 +243,7 @@
<div id="toast" role="status" aria-live="polite"></div>
{% include "OpenBench/Blocks/palette.html" %}
</body>
</html>
-7
View File
@@ -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>
+3 -1
View File
@@ -25,6 +25,8 @@
title="{% if usable %}Resume the pipeline to start it{% else %}Fix the pipeline settings first{% endif %}">Start run</button>
{% endif %}
<a class="anchorbutton btn-start" href="/pipelines/{{ pipeline.id }}/edit/">Edit</a>
<form method="post" action="/pipelines/{{ pipeline.id }}/toggle/">
{% csrf_token %}
<button class="anchorbutton btn-start" type="submit">{% if pipeline.enabled %}Pause{% else %}Resume{% endif %}</button>
@@ -54,7 +56,7 @@
<div class="banner error-message" role="alert">
<i class="fa-solid fa-circle-exclamation banner-icon"></i>
<pre>This pipeline cannot run because its settings are damaged. An administrator can fix them on the admin site.</pre>
<pre>This pipeline cannot run because its settings are damaged. Use Edit to fix them.</pre>
</div>
{% endif %}
+892
View File
@@ -0,0 +1,892 @@
{% extends "OpenBench/base.html" %}
{% block page_head %}
<div>
<a class="crumb" href="{% if pipeline %}/pipelines/{{ pipeline.id }}/{% else %}/pipelines/{% endif %}"><i class="fa-solid fa-chevron-left"></i> {% if pipeline %}{{ pipeline.name }}{% else %}Pipelines{% endif %}</a>
<h1 class="page-title">{% if pipeline %}Edit pipeline{% else %}New pipeline{% endif %}</h1>
<p class="page-sub">Draw what runs, and what starts when it ends</p>
</div>
{% endblock %}
{% block content %}
<style>
.ed input, .ed select, .ed textarea { font: inherit; color: inherit; background: transparent; border: 1px solid var(--line-strong, rgba(128, 128, 128, .4)); border-radius: var(--radius, 4px); padding: .35rem .5rem; box-sizing: border-box; }
.ed select option { background: var(--color2, #1c2230); color: var(--color-font1, inherit); }
.ed textarea { resize: vertical; width: 100%; }
.ed label { display: block; font-size: .8rem; opacity: .75; margin-bottom: .2rem; }
.ed summary { cursor: pointer; }
.ed-small { font-size: .85rem; padding: .25rem .6rem; }
.ed-pad { padding: 0 .9rem .9rem; }
.ed-note { font-size: .85rem; opacity: .8; margin: .3rem 0; }
.ed-h { margin: 1rem 0 .4rem; font-size: .9rem; }
.ed-inline { display: flex; flex-wrap: wrap; gap: .45rem; align-items: center; }
.ed-top { display: flex; flex-wrap: wrap; gap: .75rem 1.25rem; align-items: flex-end; padding: .9rem; }
.ed-title { flex: 1 1 18rem; }
.ed-title input { width: 100%; }
.ed-work { display: grid; grid-template-columns: minmax(0, 1fr) 25rem; gap: 1rem; align-items: start; margin-bottom: 1rem; }
@media (max-width: 70rem) { .ed-work { grid-template-columns: minmax(0, 1fr); } }
.ed-canvas { position: relative; overflow: auto; padding: 14px 12px 12px; min-height: 12rem; }
.ed-canvas svg { display: block; max-width: none; }
.ed-hint { margin: 0; padding: 0 .9rem .8rem; font-size: .85rem; color: var(--muted, inherit); }
.ed-hint-warn { color: var(--warn, #f5b941); }
.ed-canvas g.pl-node, .ed-canvas g.pl-edge { cursor: pointer; }
.ed-canvas g.pl-node:hover .pl-box { stroke-width: 2; }
.ed-canvas g.pl-edge:hover .pl-line { stroke-width: 2.6; }
.ed-canvas g.pl-node.ed-sel .pl-box { stroke: var(--accent-hover, #6ea2ff); stroke-width: 2.6; fill: var(--accent-soft, rgba(76, 141, 255, .15)); }
.ed-canvas g.pl-edge.ed-sel .pl-line { stroke-width: 3.4; }
.ed-canvas g.pl-edge.ed-sel .pl-label rect { stroke: var(--accent-hover, #6ea2ff); }
.ed-canvas g.pl-node.ed-bad .pl-box { stroke: var(--bad, #f87171); stroke-dasharray: 5 3; }
.ed-canvas g.pl-node.ed-warn .pl-box { stroke: var(--warn, #f5b941); stroke-dasharray: 5 3; }
.ed-canvas .ed-hit { fill: none; stroke: transparent; stroke-width: 16; pointer-events: stroke; }
.ed-plus { cursor: pointer; }
.ed-plus circle { fill: var(--color2, #1c2230); stroke: var(--accent, #4c8dff); stroke-width: 1.5; }
.ed-plus path { fill: none; stroke: var(--accent-hover, #6ea2ff); stroke-width: 1.8; stroke-linecap: round; }
.ed-plus:hover circle { fill: var(--accent, #4c8dff); }
.ed-plus:hover path { stroke: #fff; }
.ed-menu { position: absolute; z-index: 6; width: 12rem; padding: .3rem; background: var(--color2, #1c2230); border: 1px solid var(--line-strong, rgba(128, 128, 128, .4)); border-radius: var(--radius, 4px); box-shadow: 0 6px 20px rgba(0, 0, 0, .35); }
.ed-menu[hidden] { display: none; }
.ed-menu-title { padding: .25rem .5rem; font-size: .75rem; color: var(--muted, inherit); }
.ed-menu-item { display: flex; align-items: center; gap: .55rem; width: 100%; padding: .4rem .5rem; background: none; border: 0; border-radius: var(--radius, 4px); color: var(--color-font1, inherit); font: inherit; text-align: left; cursor: pointer; }
.ed-menu-item:hover { background: var(--surface-hover, rgba(128, 128, 128, .15)); }
.ed-menu-item small { margin-left: auto; color: var(--muted, inherit); }
.ed-menu-passed i { color: var(--ok, #34d399); }
.ed-menu-failed i { color: var(--bad, #f87171); }
.ed-menu-stopped i { color: var(--warn, #f5b941); }
.ed-menu-any i { color: var(--muted, inherit); }
.ed-panel { position: sticky; top: 1rem; max-height: calc(100vh - 2rem); overflow: auto; }
.ed-tag { padding: .1rem .55rem; border-radius: 999px; font-size: .75rem; background: var(--accent-soft, rgba(76, 141, 255, .15)); color: var(--accent-hover, inherit); }
.ed-box { border: 1px solid var(--line, rgba(128, 128, 128, .3)); border-radius: 8px; padding: .7rem; margin: 0 0 .6rem; }
.ed-picked { border-color: var(--accent-hover, #6ea2ff); box-shadow: inset 2px 0 0 var(--accent, #4c8dff); }
.ed-rule details { margin-top: .5rem; font-size: .85rem; }
.ed-group { margin-top: .8rem; }
.ed-group > summary { font-weight: 600; font-size: .85rem; }
.ed-grid { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: .5rem .6rem; margin-top: .5rem; }
.ed-field input, .ed-field select { width: 100%; }
.ed-wide { grid-column: 1 / -1; }
.ed-empty { border-color: var(--bad, #d9534f) !important; }
.ed-set-row { display: grid; grid-template-columns: 7rem minmax(0, 1fr) auto; gap: .4rem; align-items: center; margin: .4rem 0; }
.ed-set-row label { margin: 0; }
.ed-jump { cursor: pointer; }
.ed-jump:hover { background: var(--surface-hover, rgba(128, 128, 128, .12)); }
.pl-check-ok i { color: var(--ok, #34d399); }
.ed-limits { padding: .9rem; }
.ed-actions { display: flex; gap: .75rem; align-items: center; margin: 1rem 0; }
</style>
<form id="pl-form" class="ed" method="post" autocomplete="off">
{% csrf_token %}
<input type="hidden" name="graph" id="pl-graph" value="">
<div class="card">
<div class="ed-top">
<div class="ed-title">
<label for="pl-name">Name</label>
<input id="pl-name" name="name" value="{{ name }}" maxlength="128" required placeholder="For example: STC, then LTC if it passes">
</div>
<div>
<label>Add a step that is not connected yet</label>
<div class="ed-inline">
<button type="button" id="pl-add-test" class="anchorbutton btn-blue ed-small"><i class="fa-solid fa-plus"></i> Test</button>
<button type="button" id="pl-add-tune" class="anchorbutton btn-blue ed-small"><i class="fa-solid fa-plus"></i> Tune</button>
<button type="button" id="pl-add-datagen" class="anchorbutton btn-blue ed-small"><i class="fa-solid fa-plus"></i> Datagen</button>
</div>
</div>
</div>
</div>
<div class="ed-work">
<div class="card">
<div class="card-head"><h2 class="card-title">Flow</h2></div>
<div class="ed-canvas" id="pl-canvas">
<div id="pl-stage"></div>
<div class="ed-menu" id="pl-menu" role="menu" hidden></div>
</div>
<p class="ed-hint" id="pl-hint"></p>
</div>
<div class="card ed-panel" id="pl-panel"></div>
</div>
<div class="card">
<div class="card-head"><h2 class="card-title">Checks</h2></div>
<ul class="pl-checks" id="pl-checks">
{% for issue in issues %}
<li class="pl-check pl-check-{{ issue.level }}">
<i class="fa-solid {% if issue.level == 'error' %}fa-circle-exclamation{% elif issue.level == 'warning' %}fa-triangle-exclamation{% else %}fa-circle-info{% endif %}"></i>
<span>{% if issue.name %}<strong>{{ issue.name }}</strong> {% endif %}{{ issue.message }}</span>
</li>
{% endfor %}
</ul>
</div>
<div class="card">
<details class="ed-limits">
<summary>Limits, so that a loop can never run forever</summary>
<div class="ed-inline" style="margin-top: .7rem; gap: .75rem 1.25rem">
<div>
<label for="pl-visits">Most runs of one step</label>
<input id="pl-visits" type="number" min="1" style="width: 7rem">
</div>
<div>
<label for="pl-total">Most tests in one run</label>
<input id="pl-total" type="number" min="1" style="width: 7rem">
</div>
</div>
</details>
</div>
<div class="ed-actions">
<button type="submit" class="anchorbutton btn-blue">Save pipeline</button>
<a href="{% if pipeline %}/pipelines/{{ pipeline.id }}/{% else %}/pipelines/{% endif %}">Cancel</a>
</div>
</form>
{{ graph|json_script:"graph-data" }}
{{ meta|json_script:"meta-data" }}
<script>
(function () {
'use strict';
const NS = 'http://www.w3.org/2000/svg';
const meta = JSON.parse(document.getElementById('meta-data').textContent);
const seed = JSON.parse(document.getElementById('graph-data').textContent);
const form = document.getElementById('pl-form');
const token = form.querySelector('input[name=csrfmiddlewaretoken]').value;
const stage = document.getElementById('pl-stage');
const menu = document.getElementById('pl-menu');
const panel = document.getElementById('pl-panel');
const hint = document.getElementById('pl-hint');
const checks = document.getElementById('pl-checks');
const isObj = value => value !== null && typeof value === 'object' && !Array.isArray(value);
const root = isObj(seed) ? seed : {};
const texts = obj => {
const out = {};
if (isObj(obj)) Object.keys(obj).forEach(key => { out[key] = String(obj[key]); });
return out;
};
// Words
const OUTCOME_TEXT = { passed : 'it passes', failed : 'it fails', stopped : 'it is stopped', any : 'it ends, however it ends' };
const MENU_TEXT = { passed : 'If it passes', failed : 'If it fails', stopped : 'If it is stopped', any : 'However it ends' };
const MENU_ICON = { passed : 'fa-check', failed : 'fa-xmark', stopped : 'fa-stop', any : 'fa-arrows-rotate' };
const KIND_LABEL = { TEST : 'Test (SPRT or fixed games)', TUNE : 'Tune (SPSA)', DATAGEN : 'Datagen' };
const IMPOSSIBLE = { TUNE : ['failed'], DATAGEN : ['failed'] }; // A finished tune or datagen always passes
const OPTIONAL = ['dev_bench', 'base_bench'];
const LABEL = {
engine : 'Engine', repo : 'Repository', branch : 'Branch', network : 'Network', options : 'UCI options',
time_control : 'Time control', bench : 'Bench',
book_name : 'Opening book', upload_pgns : 'Upload PGNs', priority : 'Priority', throughput : 'Throughput',
syzygy_wdl : 'Syzygy WDL', syzygy_adj : 'Syzygy adjudication', win_adj : 'Win adjudication', draw_adj : 'Draw adjudication',
workload_size : 'Games per workload', test_mode : 'Mode', test_bounds : 'SPRT bounds',
test_confidence : 'SPRT confidence', test_max_games : 'Number of games',
spsa_alpha : 'Alpha', spsa_gamma : 'Gamma', spsa_A_ratio : 'A ratio', spsa_iterations : 'Iterations',
spsa_pairs_per : 'Pairs per iteration', spsa_reporting_type : 'Reporting', spsa_distribution_type : 'Distribution',
spsa_inputs : 'Parameters',
datagen_max_games : 'Games', datagen_custom_genfens : 'Custom genfens', datagen_play_reverses : 'Play reverses',
};
function label(key) {
const side = key.startsWith('dev_') ? 'dev_' : key.startsWith('base_') ? 'base_' : '';
return LABEL[key] || LABEL[key.slice(side.length)] || key;
}
function fullLabel(key) {
const side = key.startsWith('dev_') ? 'Dev ' : key.startsWith('base_') ? 'Base ' : '';
return side + label(key).toLowerCase();
}
const GROUP_ORDER = ['Match', 'Dev', 'Base', 'SPSA', 'Datagen', 'Advanced'];
const GROUP_TITLE = {
Match : 'Games', Dev : 'Dev (the change)', Base : 'Base (what it is compared with)',
SPSA : 'SPSA', Datagen : 'Datagen', Advanced : 'Advanced',
};
function groupOf(key) {
if (key.startsWith('dev_')) return 'Dev';
if (key.startsWith('base_')) return 'Base';
if (key.startsWith('spsa_')) return 'SPSA';
if (key.startsWith('datagen_')) return 'Datagen';
if (key.startsWith('test_') || key === 'book_name' || key === 'workload_size') return 'Match';
return 'Advanced';
}
const CHOICES = { test_mode : ['SPRT', 'GAMES'], upload_pgns : ['FALSE', 'TRUE'] };
const LONG = ['spsa_inputs', 'datagen_custom_genfens'];
// The model: what the editor is showing, which build() turns back into a graph
const model = {
start : typeof root.start === 'string' ? root.start : '',
max_visits : root.max_visits == null ? '' : String(root.max_visits),
max_steps : root.max_steps == null ? '' : String(root.max_steps),
steps : Object.entries(isObj(root.steps) ? root.steps : {}).map(([id, step]) => ({
id : id,
name : (isObj(step) && step.name) || id,
kind : (isObj(step) && step.kind) || 'TEST',
payload : texts(isObj(step) ? step.payload : {}),
msg : '',
})),
edges : (Array.isArray(root.edges) ? root.edges : []).filter(isObj).map(edge => ({
from : edge.from,
on : edge.on,
to : edge.to == null ? '' : edge.to,
set : texts(edge.set),
})),
};
const sel = { step : null, edge : null };
let lastIssues = [];
const stepById = id => model.steps.find(step => step.id === id);
const nameOf = step => (step && (step.name || step.id)) || '';
// Small DOM helpers. Text always goes in as text, never as HTML
function el(tag, attrs, ...kids) {
const node = document.createElement(tag);
for (const [key, value] of Object.entries(attrs || {})) {
if (value === false || value == null) continue;
if (key === 'class') node.className = value;
else node.setAttribute(key, value === true ? '' : value);
}
for (const kid of kids.flat()) {
if (kid != null) node.append(kid);
}
return node;
}
function svgEl(tag, attrs, ...kids) {
const node = document.createElementNS(NS, tag);
for (const [key, value] of Object.entries(attrs || {})) node.setAttribute(key, value);
kids.forEach(kid => node.append(kid));
return node;
}
function button(content, handler, cls) {
const node = el('button', { type : 'button', class : 'anchorbutton ' + (cls || 'btn-blue') + ' ed-small' }, content);
node.addEventListener('click', handler);
return node;
}
// Steps and what they need
function needed(step) {
const keys = (meta.required[step.kind] || []).slice();
if (step.kind === 'TEST') {
const mode = step.payload.test_mode || 'SPRT';
(meta.conditional[mode] || []).forEach(key => keys.push(key));
}
return keys;
}
function fieldsFor(step) {
const keys = needed(step);
OPTIONAL.forEach(key => { if (key === 'dev_bench' || step.kind !== 'TUNE') keys.push(key); });
return keys.filter((key, index) => keys.indexOf(key) === index);
}
function scaffold(step) {
const defaults = meta.defaults[step.kind] || {};
needed(step).forEach(key => {
if (!(key in step.payload)) step.payload[key] = defaults[key] == null ? '' : String(defaults[key]);
});
}
function nextId() {
const taken = new Set(model.steps.map(step => step.id));
let n = model.steps.length + 1;
while (taken.has('step' + n)) n++;
return 'step' + n;
}
// A step that follows another starts out as a copy of it: the next one is usually the same test, longer
function newStep(kind, from) {
const source = from && from.kind === kind ? from.payload : meta.defaults[kind];
const step = { id : nextId(), name : 'Step ' + (model.steps.length + 1), kind : kind, payload : texts(source), msg : '' };
scaffold(step);
model.steps.push(step);
return step;
}
function changeKind(step, kind) {
const allowed = new Set(meta.allowed);
const kept = {};
Object.keys(step.payload).forEach(key => { if (allowed.has(key)) kept[key] = step.payload[key]; });
step.kind = kind;
step.payload = Object.assign(texts(meta.defaults[kind]), kept);
scaffold(step);
}
function removeStep(step) {
model.steps.splice(model.steps.indexOf(step), 1);
model.edges = model.edges.filter(edge => edge.from !== step.id && edge.to !== step.id);
if (model.start === step.id) model.start = model.steps[0].id;
select(model.start);
changed();
}
// Turn the model back into a graph
function build() {
const steps = {};
model.steps.forEach(step => {
const payload = {};
Object.keys(step.payload).forEach(key => { if (key.trim()) payload[key.trim()] = step.payload[key]; });
steps[step.id] = { name : step.name, kind : step.kind, payload : payload };
});
const edges = model.edges.map(edge => {
const out = { from : edge.from, on : edge.on, to : edge.to === '' ? null : edge.to };
const set = {};
Object.keys(edge.set).forEach(key => { if (key.trim()) set[key.trim()] = edge.set[key]; });
if (Object.keys(set).length) out.set = set;
return out;
});
const graph = { version : 1, start : model.start, steps : steps, edges : edges };
const visits = parseInt(model.max_visits, 10);
const total = parseInt(model.max_steps, 10);
if (!isNaN(visits)) graph.max_visits = visits;
if (!isNaN(total)) graph.max_steps = total;
return graph;
}
// The flow, drawn by the server, with the very same code that draws a run
let timer = null;
let ticket = 0;
function changed() {
drawHint();
clearTimeout(timer);
timer = setTimeout(refresh, 250);
}
async function refresh() {
const mine = ++ticket;
const body = new FormData();
body.append('csrfmiddlewaretoken', token);
body.append('graph', JSON.stringify(build()));
try {
const response = await fetch('/pipelines/preview/', { method : 'POST', body : body, credentials : 'same-origin' });
const data = await response.json();
if (mine !== ticket) return;
drawCanvas(data.svg || '');
showIssues(data.issues || [{ level : 'error', step : null, message : data.error || 'The check failed' }]);
} catch (error) {
if (mine !== ticket) return;
showIssues([{ level : 'error', step : null, message : 'The flow could not be drawn. Reload the page and try again' }]);
}
}
const nodeFor = id => Array.from(stage.querySelectorAll('g.pl-node')).find(node => node.getAttribute('data-step') === id);
const edgeFor = index => Array.from(stage.querySelectorAll('g.pl-edge')).find(node => node.getAttribute('data-edge') === String(index));
function drawCanvas(markup) {
closeMenu();
if (!markup) {
stage.replaceChildren(el('p', { class : 'ed-note' }, 'The flow cannot be drawn yet. The checks below say why.'));
return;
}
stage.innerHTML = markup; // Escaped by the server, which is the only place that writes it
const svg = stage.querySelector('svg');
if (!svg) return;
// A wide invisible copy of every arrow, so that a thin line is easy to hit
svg.querySelectorAll('g.pl-edge').forEach(group => {
const line = group.querySelector('.pl-line');
if (!line) return;
const hit = line.cloneNode(false);
hit.setAttribute('class', 'ed-hit');
hit.removeAttribute('marker-end');
group.insertBefore(hit, line);
});
// A + on top of every step: this is where the next step comes from
svg.querySelectorAll('g.pl-node').forEach(group => {
const box = group.querySelector('.pl-box');
if (!box) return;
const x = Number(box.getAttribute('x')) + Number(box.getAttribute('width')) / 2;
const y = Number(box.getAttribute('y'));
svg.append(svgEl('g', { class : 'ed-plus', 'data-plus' : group.getAttribute('data-step') },
svgEl('title', {}, 'Add what happens next'),
svgEl('circle', { cx : x, cy : y, r : 11 }),
svgEl('path', { d : 'M' + (x - 5) + ' ' + y + ' h10 M' + x + ' ' + (y - 5) + ' v10' })));
});
applyMarks();
}
function applyMarks() {
stage.querySelectorAll('.ed-sel, .ed-bad, .ed-warn').forEach(node => node.classList.remove('ed-sel', 'ed-bad', 'ed-warn'));
const worst = {};
lastIssues.forEach(issue => {
if (typeof issue.step !== 'string') return;
if (issue.level === 'error') worst[issue.step] = 'ed-bad';
else if (issue.level === 'warning' && !worst[issue.step]) worst[issue.step] = 'ed-warn';
});
Object.keys(worst).forEach(id => { const node = nodeFor(id); if (node) node.classList.add(worst[id]); });
if (sel.step !== null) { const node = nodeFor(sel.step); if (node) node.classList.add('ed-sel'); }
if (sel.edge !== null) { const node = edgeFor(sel.edge); if (node) node.classList.add('ed-sel'); }
}
stage.addEventListener('click', event => {
const plus = event.target.closest('.ed-plus');
if (plus) { openMenu(plus.getAttribute('data-plus')); return; }
const edge = event.target.closest('g.pl-edge');
if (edge) { selectEdge(Number(edge.getAttribute('data-edge'))); return; }
const node = event.target.closest('g.pl-node');
if (node) { select(node.getAttribute('data-step')); return; }
closeMenu();
});
// The + menu: what should start, and when
function closeMenu() { menu.hidden = true; }
function openMenu(stepId) {
const step = stepById(stepId);
const node = nodeFor(stepId);
const box = node && node.querySelector('.pl-box');
if (!step || !box) return;
const x = Number(box.getAttribute('x')) + Number(box.getAttribute('width')) / 2;
const y = Number(box.getAttribute('y'));
menu.replaceChildren(el('div', { class : 'ed-menu-title' }, 'After ' + nameOf(step)));
meta.outcomes.filter(outcome => !(IMPOSSIBLE[step.kind] || []).includes(outcome)).forEach(outcome => {
const exists = model.edges.some(edge => edge.from === stepId && edge.on === outcome);
const item = el('button', { type : 'button', class : 'ed-menu-item ed-menu-' + outcome, role : 'menuitem' },
el('i', { class : 'fa-solid ' + MENU_ICON[outcome] }), MENU_TEXT[outcome] || outcome,
exists ? el('small', {}, 'open') : null);
item.addEventListener('click', () => chain(stepId, outcome));
menu.append(item);
});
menu.style.left = Math.max(4, x - 96) + 'px';
menu.style.top = (y + 20) + 'px';
menu.hidden = false;
}
function chain(stepId, outcome) {
const from = stepById(stepId);
const existing = model.edges.find(edge => edge.from === stepId && edge.on === outcome);
if (existing) { selectEdge(model.edges.indexOf(existing)); return; }
if (model.steps.length >= meta.limits.steps) {
flash('A pipeline may have at most ' + meta.limits.steps + ' steps');
closeMenu();
return;
}
const next = newStep(from.kind, from);
model.edges.push({ from : stepId, on : outcome, to : next.id, set : {} });
select(next.id);
changed();
}
document.addEventListener('click', event => {
if (!event.target.closest('.ed-plus, #pl-menu')) closeMenu();
});
document.addEventListener('keydown', event => {
if (event.key === 'Escape') closeMenu();
});
// Selecting
function select(id) {
sel.step = id;
sel.edge = null;
closeMenu();
drawPanel();
applyMarks();
}
function selectEdge(index) {
const edge = model.edges[index];
if (!edge) return;
sel.step = edge.from;
sel.edge = index;
closeMenu();
drawPanel();
applyMarks();
const row = panel.querySelector('.ed-rule.ed-picked');
if (row) row.scrollIntoView({ block : 'nearest' });
}
function markRows() {
panel.querySelectorAll('.ed-rule').forEach(row => {
row.classList.toggle('ed-picked', Number(row.getAttribute('data-edge')) === sel.edge);
});
}
// The panel: the settings of the selected step, and what it leads to
function fillSelect(select, value, allowEnd) {
select.replaceChildren();
if (allowEnd) select.append(el('option', { value : '' }, 'end the pipeline'));
model.steps.forEach(step => select.append(el('option', { value : step.id }, 'start ' + nameOf(step))));
select.value = value;
}
function stepSelect(value, allowEnd, onChange) {
const select = el('select', { class : 'ed-step-select', 'data-end' : allowEnd ? '1' : '0', 'aria-label' : 'Step' });
fillSelect(select, value, allowEnd);
select.addEventListener('change', () => onChange(select.value));
return select;
}
function refreshSelects() {
panel.querySelectorAll('.ed-step-select').forEach(select => {
fillSelect(select, select.value, select.getAttribute('data-end') === '1');
});
}
function field(step, key, isRequired) {
const choices = CHOICES[key];
const current = step.payload[key] == null ? '' : step.payload[key];
let input;
if (choices) {
input = el('select', { 'aria-label' : fullLabel(key) }, choices.map(choice => el('option', { value : choice }, choice)));
if (!choices.includes(current)) input.append(el('option', { value : current }, current));
} else if (LONG.includes(key)) {
input = el('textarea', { rows : '4', spellcheck : 'false', 'aria-label' : fullLabel(key) });
} else {
input = el('input', { spellcheck : 'false', 'aria-label' : fullLabel(key) });
}
input.value = current;
const flag = () => input.classList.toggle('ed-empty', isRequired && input.value.trim() === '');
input.addEventListener(choices ? 'change' : 'input', () => {
step.payload[key] = input.value;
flag();
if (key === 'test_mode') { scaffold(step); drawPanel(); }
changed();
});
flag();
return el('div', { class : LONG.includes(key) ? 'ed-field ed-wide' : 'ed-field' },
el('label', {}, label(key) + (isRequired ? '' : ' (optional)')), input);
}
// The settings that a rule changes for the step that it starts
function setEditor(edge) {
const box = el('div');
const preferred = ['dev_time_control', 'base_time_control', 'test_bounds', 'test_confidence', 'test_max_games',
'dev_branch', 'base_branch', 'dev_options', 'base_options', 'dev_network', 'base_network', 'priority', 'throughput', 'workload_size', 'book_name'];
const allowed = new Set(meta.allowed);
const keys = preferred.filter(key => allowed.has(key)).concat(meta.allowed.filter(key => !preferred.includes(key)));
const draw = () => {
box.replaceChildren();
Object.keys(edge.set).forEach(key => {
const input = el('input', { spellcheck : 'false', 'aria-label' : fullLabel(key) });
input.value = edge.set[key];
input.addEventListener('input', () => { edge.set[key] = input.value; changed(); });
const remove = button('\u00d7', () => { delete edge.set[key]; draw(); changed(); }, 'btn-red');
remove.title = 'Stop changing this setting';
box.append(el('div', { class : 'ed-set-row' }, el('label', {}, fullLabel(key)), input, remove));
});
const pick = el('select', { 'aria-label' : 'Change a setting' },
el('option', { value : '' }, 'Change a setting\u2026'),
keys.filter(key => !(key in edge.set)).map(key => el('option', { value : key }, fullLabel(key))));
pick.addEventListener('change', () => {
if (!pick.value) return;
const target = stepById(edge.to) || stepById(edge.from);
edge.set[pick.value] = (target && target.payload[pick.value]) || '';
draw();
changed();
});
box.append(pick);
};
draw();
return box;
}
function ruleRow(edge, index) {
const on = el('select', { 'aria-label' : 'Outcome' }, meta.outcomes.map(outcome => el('option', { value : outcome }, OUTCOME_TEXT[outcome] || outcome)));
on.value = edge.on;
on.addEventListener('change', () => { edge.on = on.value; changed(); });
const to = stepSelect(edge.to, true, value => { edge.to = value; changed(); });
const remove = button('\u00d7', () => {
model.edges.splice(model.edges.indexOf(edge), 1);
sel.edge = null;
drawPanel();
applyMarks();
changed();
}, 'btn-red');
remove.title = 'Remove this rule';
const more = el('details', { open : Object.keys(edge.set).length > 0 || sel.edge === index },
el('summary', {}, 'Change settings for the step that starts'), setEditor(edge));
const row = el('div', { class : 'ed-box ed-rule' + (sel.edge === index ? ' ed-picked' : ''), 'data-edge' : String(index) },
el('div', { class : 'ed-inline' }, 'If', on, 'then', to, remove), more);
row.addEventListener('click', () => { sel.edge = index; applyMarks(); markRows(); });
return row;
}
function addRule(step) {
const used = model.edges.filter(edge => edge.from === step.id).map(edge => edge.on);
const options = meta.outcomes.filter(outcome => !(IMPOSSIBLE[step.kind] || []).includes(outcome));
model.edges.push({ from : step.id, on : options.find(outcome => !used.includes(outcome)) || 'any', to : '', set : {} });
sel.edge = model.edges.length - 1;
drawPanel();
applyMarks();
changed();
}
function drawPanel() {
panel.replaceChildren();
const step = stepById(sel.step);
if (!step) {
panel.append(el('div', { class : 'card-head' }, el('h2', { class : 'card-title' }, 'Step')),
el('p', { class : 'ed-note ed-pad' }, 'Click a step in the flow to change it.'));
return;
}
const head = el('div', { class : 'card-head' }, el('h2', { class : 'card-title' }, 'Step'),
model.start === step.id
? el('span', { class : 'ed-tag' }, 'First step')
: button('Make this the first step', () => { model.start = step.id; drawPanel(); changed(); }));
const body = el('div', { class : 'ed-pad' });
const name = el('input', { maxlength : '64', required : true, style : 'width: 100%', 'aria-label' : 'Step name' });
name.value = step.name;
name.addEventListener('input', () => { step.name = name.value; refreshSelects(); changed(); });
const kind = el('select', { 'aria-label' : 'Kind' }, meta.kinds.map(k => el('option', { value : k }, KIND_LABEL[k] || k)));
kind.value = step.kind;
kind.addEventListener('change', () => { changeKind(step, kind.value); drawPanel(); changed(); });
body.append(el('div', { class : 'ed-inline', style : 'align-items: flex-end' },
el('div', { style : 'flex: 1 1 9rem' }, el('label', {}, 'Name'), name),
el('div', {}, el('label', {}, 'Kind'), kind)));
if (step.msg) body.append(el('p', { class : 'ed-note' }, step.msg));
// Start from a test that already exists
if (step.kind === 'TEST') {
const number = el('input', { type : 'number', min : '1', placeholder : 'Test #', 'aria-label' : 'Test number', style : 'width: 6.5rem' });
const copy = button('Copy settings', async () => {
const id = parseInt(number.value, 10);
if (!id) { step.msg = 'Type the number of a test first'; drawPanel(); return; }
try {
const response = await fetch('/pipelines/test-fields/' + id + '/', { credentials : 'same-origin' });
const data = await response.json();
if (!response.ok) { step.msg = data.error || 'Could not copy that test'; drawPanel(); return; }
step.payload = texts(data.payload);
scaffold(step);
step.msg = 'Copied from test #' + id + '. Check the branches before saving';
} catch (error) {
step.msg = 'Could not copy that test';
}
drawPanel();
changed();
});
body.append(el('div', { style : 'margin-top: .8rem' }, el('label', {}, 'Start from a test that already exists'),
el('div', { class : 'ed-inline' }, number, copy)));
}
// The settings, in the same groups as the pages that create a test
const required = needed(step);
const groups = {};
fieldsFor(step).forEach(key => { (groups[groupOf(key)] = groups[groupOf(key)] || []).push(key); });
GROUP_ORDER.forEach(title => {
if (!groups[title]) return;
const grid = el('div', { class : 'ed-grid' }, groups[title].map(key => field(step, key, required.includes(key))));
const empty = groups[title].some(key => required.includes(key) && String(step.payload[key] == null ? '' : step.payload[key]).trim() === '');
body.append(el('details', { class : 'ed-group', open : title === 'Match' || (title !== 'Advanced' && empty) },
el('summary', {}, GROUP_TITLE[title]), grid));
});
// What it leads to
body.append(el('h3', { class : 'ed-h' }, 'What happens next'));
let leads = 0;
model.edges.forEach((edge, index) => {
if (edge.from !== step.id) return;
leads++;
body.append(ruleRow(edge, index));
});
if (!leads) body.append(el('p', { class : 'ed-note' }, 'Nothing: the pipeline ends after this step. Press + above the step in the flow, or add a rule here.'));
const remove = button('Remove this step', () => removeStep(step), 'btn-red');
remove.disabled = model.steps.length < 2;
body.append(el('div', { class : 'ed-inline', style : 'margin-top: .6rem' }, button('Add rule', () => addRule(step)), remove));
panel.append(head, body);
}
// Checks, from the server, so that they are the very same rules that a run uses
function showIssues(list) {
lastIssues = list;
checks.replaceChildren();
if (!list.length) {
checks.append(el('li', { class : 'pl-check pl-check-ok' }, el('i', { class : 'fa-solid fa-circle-check' }), el('span', {}, 'No problems found')));
applyMarks();
return;
}
list.forEach(issue => {
const icon = issue.level === 'error' ? 'fa-circle-exclamation' : issue.level === 'warning' ? 'fa-triangle-exclamation' : 'fa-circle-info';
const who = issue.name || (typeof issue.step === 'string' ? issue.step : '');
const jump = typeof issue.step === 'string' && stepById(issue.step);
const item = el('li', { class : 'pl-check pl-check-' + issue.level + (jump ? ' ed-jump' : '') },
el('i', { class : 'fa-solid ' + icon }),
el('span', {}, who ? el('strong', {}, who) : null, who ? ' ' : null, issue.message));
if (jump) item.addEventListener('click', () => select(issue.step));
checks.append(item);
});
applyMarks();
}
// The line under the flow
let flashTimer = null;
function flash(message) {
hint.textContent = message;
hint.classList.add('ed-hint-warn');
clearTimeout(flashTimer);
flashTimer = setTimeout(drawHint, 4000);
}
function drawHint() {
hint.classList.remove('ed-hint-warn');
hint.textContent = model.steps.length === 1 && !model.edges.length
? 'This is the whole pipeline so far: one step, and then it ends. Press the + above the step to say what starts when it passes or fails.'
: 'Press + above a step to add what happens next. Click a step to change its settings, or the label on an arrow to change that rule.';
}
// Toolbar, limits and saving
['TEST', 'TUNE', 'DATAGEN'].forEach(kind => {
document.getElementById('pl-add-' + kind.toLowerCase()).addEventListener('click', () => {
if (model.steps.length >= meta.limits.steps) {
flash('A pipeline may have at most ' + meta.limits.steps + ' steps');
return;
}
const step = newStep(kind, null);
select(step.id);
changed();
});
});
const visitsField = document.getElementById('pl-visits');
const totalField = document.getElementById('pl-total');
visitsField.max = meta.limits.visits;
totalField.max = meta.limits.total;
visitsField.value = model.max_visits;
totalField.value = model.max_steps;
visitsField.addEventListener('input', () => { model.max_visits = visitsField.value; changed(); });
totalField.addEventListener('input', () => { model.max_steps = totalField.value; changed(); });
form.addEventListener('submit', () => {
document.getElementById('pl-graph').value = JSON.stringify(build());
});
// Go
if (!model.steps.length) {
const first = { id : 'step1', name : 'Step 1', kind : 'TEST', payload : texts(meta.defaults.TEST), msg : '' };
scaffold(first);
model.steps.push(first);
}
if (!model.steps.some(step => step.id === model.start)) model.start = model.steps[0].id;
sel.step = model.start;
drawPanel();
drawHint();
refresh();
})();
</script>
{% endblock %}
+92
View File
@@ -0,0 +1,92 @@
{% extends "OpenBench/base.html" %}
{% block page_head %}
<div>
<a class="crumb" href="/pipelines/"><i class="fa-solid fa-chevron-left"></i> Pipelines</a>
<h1 class="page-title">New pipeline</h1>
<p class="page-sub">Type a branch and press Enter. Everything else is filled in like Create Test, and the first test starts right away</p>
</div>
{% endblock %}
{% block content %}
<style>
.quick-more { margin-top: 14px; }
.quick-more summary { cursor: pointer; margin-bottom: 12px; color: var(--color-font2, inherit); font-size: 13px; }
.quick-actions { display: flex; flex-wrap: wrap; gap: .75rem; align-items: center; }
.quick-hint { margin-top: 1rem; }
</style>
<form method="post" action="/pipelines/quick/" autocomplete="off">
{% csrf_token %}
<div class="form">
<div class="col">
<h3> What to test </h3>
<div class="row">
<label for="dev_branch"> Dev Branch </label>
<input id="dev_branch" name="dev_branch" value="{{ form.dev_branch }}" placeholder="The branch to test" spellcheck="false" autofocus required>
</div>
<div class="row">
<label for="first"> First Test </label>
<select id="first" name="first">
{% for choice in choices %}
<option value="{{ choice.name }}"{% if choice.name == form.first %} selected{% endif %}>{{ choice.name }}{% if choice.time %} ({{ choice.time }}){% endif %}</option>
{% endfor %}
</select>
</div>
<div class="row">
<label for="then"> If It Passes </label>
<select id="then" name="then">
<option value=""{% if not form.then %} selected{% endif %}>Stop there</option>
{% for choice in choices %}
<option value="{{ choice.name }}"{% if choice.name == form.then %} selected{% endif %}>Then {{ choice.name }}{% if choice.time %} ({{ choice.time }}){% endif %}</option>
{% endfor %}
</select>
</div>
<details class="quick-more"{% if more %} open{% endif %}>
<summary> More options </summary>
{% if engines|length > 1 %}
<div class="row">
<label for="engine"> Engine </label>
<select id="engine" name="engine" onchange="location.search = '?engine=' + encodeURIComponent(this.value) + '&amp;dev_branch=' + encodeURIComponent(document.getElementById('dev_branch').value);">
{% for name in engines %}
<option value="{{ name }}"{% if name == engine %} selected{% endif %}>{{ name }}</option>
{% endfor %}
</select>
</div>
{% else %}
<input type="hidden" name="engine" value="{{ engine }}">
{% endif %}
<div class="row">
<label for="base_branch"> Base Branch </label>
<input id="base_branch" name="base_branch" value="{{ form.base_branch }}" placeholder="{% if base %}{{ base }}{% else %}The branch to compare against{% endif %}" spellcheck="false"{% if not base %} required{% endif %}>
</div>
<div class="row">
<label for="name"> Name </label>
<input id="name" name="name" value="{{ form.name }}" placeholder="The branch, and what runs" maxlength="128" spellcheck="false">
</div>
</details>
</div>
</div>
<div class="form-actions">
<div class="quick-actions">
<button type="submit" name="action" value="run" class="anchorbutton btn-blue">Run pipeline</button>
<button type="submit" name="action" value="save" class="anchorbutton btn-start">Save without running</button>
</div>
</div>
</form>
<p class="muted-small quick-hint">Need to retry, branch on a failure, or tune? <a href="/pipelines/new/">Draw the flow in the editor</a>.</p>
{% endblock %}
+6 -1
View File
@@ -5,6 +5,11 @@
<h1 class="page-title">Pipelines</h1>
<p class="page-sub">Run a test, then let its result decide what runs next</p>
</div>
<div class="page-actions">
<a class="anchorbutton btn-blue" href="/pipelines/quick/">New pipeline</a>
<a class="anchorbutton btn-start" href="/pipelines/new/">Flow editor</a>
</div>
{% endblock %}
{% block content %}
@@ -63,7 +68,7 @@
<div class="empty-state">
<i class="fa-solid fa-diagram-project"></i>
<p>No pipelines yet.</p>
<p class="muted-small">A pipeline starts a test and picks the next one from the result. An administrator adds them on the admin site for now.</p>
<p class="muted-small">A pipeline starts a test and picks the next one from the result. Use New pipeline to create the first one.</p>
</div>
</div>
+83 -13
View File
@@ -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 %}
@@ -21,14 +25,15 @@
</div>
{% endif %}
<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>
@@ -75,7 +80,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>
@@ -220,8 +225,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">
@@ -242,11 +311,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>
@@ -265,7 +334,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>
@@ -275,8 +344,9 @@
</tr>
{% endfor %}
</table>
</div>
{% if type == "TUNE" %}</details>{% else %}</div>{% endif %}
{% if type == "TUNE" %}</div><!-- /tune-main -->{% endif %}
</div>
{% endblock %}
{% endblock %}
+304
View File
@@ -0,0 +1,304 @@
#!/usr/bin/python3
import os
import sys
import unittest
# Needed to include from ../OpenBench/pipeline_defaults.py, which has no Django dependencies
PARENT = os.path.join(os.path.dirname(os.path.abspath(__file__)), os.path.pardir)
sys.path.insert(0, os.path.abspath(PARENT))
from OpenBench.pipeline_defaults import *
from OpenBench.pipeline_graph import ALLOWED_FIELDS, REQUIRED_FIELDS, has_errors, validate_graph
# The shape of a real engine config ( Engines/Eleanor.json ), presets only
ENGINE = {
'source' : 'https://github.com/o/Engine',
'test_presets' : {
'default' : {
'base_branch' : 'main', 'book_name' : 'UHO.epd',
'test_bounds' : '[0.00, 5.00]', 'test_confidence' : '[0.05, 0.05]',
'win_adj' : 'movecount=3 score=400', 'draw_adj' : 'movenumber=40 movecount=8 score=10',
},
'STC' : { 'both_options' : 'Threads=1 Hash=8', 'both_time_control' : '8.0+0.08', 'workload_size' : 32 },
'LTC' : { 'both_options' : 'Threads=1 Hash=64', 'both_time_control' : '40.0+0.4', 'workload_size' : 8 },
},
}
NETWORKS = [
{ 'engine' : 'Engine', 'name' : 'old.nn', 'sha256' : 'aaaaaaaa', 'default' : False },
{ 'engine' : 'Engine', 'name' : 'newest.nn', 'sha256' : 'bbbbbbbb', 'default' : True },
{ 'engine' : 'Other', 'name' : 'other.nn', 'sha256' : 'cccccccc', 'default' : True },
]
def build(preset='STC', branch='dev', engine_config=ENGINE, **kwargs):
return test_payload('Engine', engine_config, preset, branch, **kwargs)
def with_presets(**presets):
return { 'source' : ENGINE['source'], 'test_presets' : dict(ENGINE['test_presets'], **presets) }
class PresetTests(unittest.TestCase):
def test_the_names_leave_out_the_defaults(self):
self.assertEqual(preset_names(ENGINE), ['STC', 'LTC'])
def test_an_engine_without_presets_has_none(self):
self.assertEqual(preset_names({}), [])
self.assertEqual(preset_names({ 'test_presets' : None }), [])
def test_both_goes_to_the_dev_and_the_base_alike(self):
payload, _ = build('LTC')
self.assertEqual((payload['dev_options'], payload['base_options']), ('Threads=1 Hash=64', 'Threads=1 Hash=64'))
self.assertEqual((payload['dev_time_control'], payload['base_time_control']), ('40.0+0.4', '40.0+0.4'))
def test_the_defaults_come_first_and_a_preset_wins_over_them(self):
engine = with_presets(Slow={ 'test_bounds' : '[-1.00, 3.00]', 'base_branch' : 'master',
'both_options' : 'Threads=1 Hash=8', 'both_time_control' : '1+1' })
payload, missing = build('Slow', engine_config=engine)
self.assertEqual(payload['test_bounds'], '[-1.00, 3.00]') # The preset
self.assertEqual(payload['base_branch'], 'master') # The preset
self.assertEqual(payload['test_confidence'], '[0.05, 0.05]') # The default, untouched
self.assertEqual(missing, [])
def test_the_time_control_of_a_preset_for_showing(self):
self.assertEqual((time_control(ENGINE, 'STC'), time_control(ENGINE, 'LTC')), ('8.0+0.08', '40.0+0.4'))
self.assertEqual(time_control(ENGINE, 'nope'), '')
class PayloadTests(unittest.TestCase):
def test_one_branch_is_all_that_it_takes(self):
payload, missing = build(branch='my-branch')
self.assertEqual(missing, [])
self.assertEqual(payload['dev_branch'], 'my-branch')
self.assertEqual(payload['base_branch'], 'main')
self.assertEqual(payload['test_mode'], 'SPRT')
self.assertEqual(payload['workload_size'], '32')
def test_it_starts_out_like_the_create_test_page(self):
payload, _ = build()
for key, value in FORM_DEFAULTS.items():
self.assertEqual(payload[key], value, key)
self.assertEqual(payload['syzygy_wdl'], 'DISABLED') # The page says disabled, whatever the editor said
self.assertEqual((payload['priority'], payload['throughput']), ('0', '1000'))
def test_every_setting_that_a_step_needs_is_there_and_is_text(self):
for preset in ('STC', 'LTC'):
payload, missing = build(preset)
self.assertEqual(missing, [])
for key in REQUIRED_FIELDS['TEST'] + ['test_bounds', 'test_confidence']:
self.assertIn(key, payload, key)
self.assertTrue(all(isinstance(value, str) for value in payload.values()))
self.assertTrue(set(payload) <= ALLOWED_FIELDS)
def test_engine_and_repo_are_the_engines_own_unless_the_profile_says_otherwise(self):
payload, _ = build()
self.assertEqual((payload['dev_engine'], payload['base_engine']), ('Engine', 'Engine'))
self.assertEqual((payload['dev_repo'], payload['base_repo']), ('https://github.com/o/Engine',) * 2)
payload, _ = build(repos={ 'Engine' : 'https://github.com/me/Engine' })
self.assertEqual((payload['dev_repo'], payload['base_repo']), ('https://github.com/me/Engine',) * 2)
payload, _ = build(repos={ 'Another' : 'https://github.com/me/Another' }) # Not for this engine
self.assertEqual(payload['dev_repo'], 'https://github.com/o/Engine')
payload, _ = build(repos=None) # A profile with nothing saved
self.assertEqual(payload['dev_repo'], 'https://github.com/o/Engine')
def test_the_base_branch_can_be_chosen(self):
payload, missing = build(base_branch='release')
self.assertEqual((payload['base_branch'], missing), ('release', []))
def test_a_missing_base_branch_is_reported_not_guessed(self):
engine = { 'source' : 'x', 'test_presets' : { 'STC' : ENGINE['test_presets']['STC'],
'default' : { 'book_name' : 'b.epd', 'test_bounds' : '[0.00, 5.00]', 'test_confidence' : '[0.05, 0.05]' } } }
self.assertEqual(build(engine_config=engine)[1], ['base_branch'])
self.assertEqual(build(engine_config=engine, base_branch='main')[1], [])
def test_what_the_presets_leave_out_is_reported(self):
engine = { 'source' : 'x', 'test_presets' : { 'default' : { 'base_branch' : 'main', 'book_name' : 'b.epd',
'test_bounds' : '[0.00, 5.00]', 'test_confidence' : '[0.05, 0.05]' }, 'Bare' : {} } }
payload, missing = build('Bare', engine_config=engine)
self.assertEqual(sorted(missing), ['base_options', 'base_time_control', 'dev_options', 'dev_time_control'])
self.assertEqual(payload['workload_size'], FALLBACKS['workload_size']) # These have a standard value
self.assertEqual(payload['win_adj'], FALLBACKS['win_adj'])
def test_an_engine_that_names_no_book_gets_the_first_one_there_is(self):
engine = with_presets(default={ 'base_branch' : 'main', 'test_bounds' : '[0.00, 5.00]', 'test_confidence' : '[0.05, 0.05]' })
self.assertEqual(build(engine_config=engine, books=['one.epd', 'two.epd'])[0]['book_name'], 'one.epd')
self.assertEqual(build(engine_config=engine)[1], ['book_name'])
def test_an_unknown_preset_only_has_the_defaults_to_go_on(self):
_, missing = build('nope')
self.assertIn('dev_time_control', missing)
def test_whatever_else_a_preset_holds_is_left_out(self):
engine = with_presets(Odd={ 'both_options' : 'Threads=1 Hash=8', 'both_time_control' : '1+1', 'rubbish' : 'x' })
payload, _ = build('Odd', engine_config=engine)
self.assertNotIn('rubbish', payload)
def test_a_bench_that_a_preset_gives_is_kept_and_otherwise_it_is_left_to_autofill(self):
self.assertNotIn('dev_bench', build()[0])
engine = with_presets(Fixed={ 'both_bench' : 12345, 'both_options' : 'Threads=1 Hash=8', 'both_time_control' : '1+1' })
payload, _ = build('Fixed', engine_config=engine)
self.assertEqual((payload['dev_bench'], payload['base_bench']), ('12345', '12345'))
class ModeTests(unittest.TestCase):
def test_a_preset_of_fixed_games_is_a_games_test(self):
engine = with_presets(Fixed={ 'both_options' : 'Threads=1 Hash=8', 'both_time_control' : '1+1', 'test_max_games' : 40000 })
payload, missing = build('Fixed', engine_config=engine)
self.assertEqual((payload['test_mode'], payload['test_max_games'], missing), ('GAMES', '40000', []))
self.assertNotIn('test_bounds', payload); self.assertNotIn('test_confidence', payload)
def test_sprt_leaves_the_number_of_games_out(self):
engine = with_presets(default=dict(ENGINE['test_presets']['default'], test_max_games=100))
payload, _ = build(engine_config=engine)
self.assertEqual(payload['test_mode'], 'GAMES') # The last word of the page, as it is for a person
self.assertEqual(build()[0]['test_mode'], 'SPRT')
self.assertNotIn('test_max_games', build()[0])
def test_bounds_after_games_make_it_sprt_again(self):
engine = with_presets(Both={ 'both_options' : 'Threads=1 Hash=8', 'both_time_control' : '1+1',
'test_max_games' : 100, 'test_bounds' : '[0.00, 2.00]' })
payload, _ = build('Both', engine_config=engine)
self.assertEqual(payload['test_mode'], 'SPRT')
self.assertNotIn('test_max_games', payload)
class NetworkTests(unittest.TestCase):
def test_the_default_network_of_the_engine(self):
self.assertEqual(build(networks=NETWORKS)[0]['dev_network'], 'bbbbbbbb')
self.assertEqual(build(networks=NETWORKS)[0]['base_network'], 'bbbbbbbb')
def test_no_default_means_no_network(self):
self.assertEqual(build(networks=NETWORKS[:1])[0]['dev_network'], '')
self.assertEqual(build()[0]['dev_network'], '')
def test_a_network_of_another_engine_is_never_used(self):
self.assertEqual(default_network(NETWORKS, 'Nothing'), '')
self.assertEqual(default_network(NETWORKS, 'Other'), 'cccccccc')
def test_the_last_default_wins_like_it_does_on_the_page(self):
twice = NETWORKS + [{ 'engine' : 'Engine', 'name' : 'later.nn', 'sha256' : 'dddddddd', 'default' : True }]
self.assertEqual(default_network(twice, 'Engine'), 'dddddddd')
def test_a_preset_may_name_a_network_or_give_its_hash(self):
for wanted in ('old.nn', 'aaaaaaaa'):
engine = with_presets(Net={ 'both_network' : wanted, 'both_options' : 'Threads=1 Hash=8', 'both_time_control' : '1+1' })
self.assertEqual(build('Net', engine_config=engine, networks=NETWORKS)[0]['dev_network'], 'aaaaaaaa', wanted)
def test_a_preset_may_ask_for_none(self):
engine = with_presets(Net={ 'both_network' : 'None', 'both_options' : 'Threads=1 Hash=8', 'both_time_control' : '1+1' })
self.assertEqual(build('Net', engine_config=engine, networks=NETWORKS)[0]['dev_network'], '')
def test_a_network_that_does_not_exist_changes_nothing(self):
engine = with_presets(Net={ 'both_network' : 'ghost.nn', 'both_options' : 'Threads=1 Hash=8', 'both_time_control' : '1+1' })
self.assertEqual(build('Net', engine_config=engine, networks=NETWORKS)[0]['dev_network'], 'bbbbbbbb')
def test_having_no_network_is_not_a_missing_setting(self):
self.assertEqual(build(networks=[])[1], [])
class BranchTests(unittest.TestCase):
def test_what_a_branch_may_look_like(self):
for text in ('main', 'feature/new-search_2', 'v1.2.3', 'a' * 255, '0' * 40, ' padded '):
self.assertEqual(clean_branch(text), text.strip(), text)
def test_what_it_may_not(self):
for text in (None, '', ' ', 'two words', 'tab\there', 'quote"d', "it's", 'back\\slash', 'a' * 256, 'new\nline'):
self.assertIsNone(clean_branch(text), repr(text))
class GraphTests(unittest.TestCase):
def steps(self, *presets):
return [(preset, build(preset)[0]) for preset in presets]
def test_a_graph_of_one_step_is_sound(self):
graph = quick_graph(self.steps('STC'))
self.assertFalse(has_errors(validate_graph(graph)))
self.assertEqual((graph['start'], list(graph['steps']), graph['edges']), ('step1', ['step1'], []))
def test_the_next_one_starts_when_the_one_before_passed(self):
graph = quick_graph(self.steps('STC', 'LTC'))
issues = validate_graph(graph)
self.assertFalse(has_errors(issues))
self.assertEqual([issue['level'] for issue in issues], ['info', 'info']) # Only "it ends here if it fails or stops"
self.assertEqual(graph['edges'], [{ 'from' : 'step1', 'on' : 'passed', 'to' : 'step2' }])
self.assertEqual([step['name'] for step in graph['steps'].values()], ['STC', 'LTC'])
def test_any_number_of_steps_make_a_chain(self):
graph = quick_graph(self.steps('STC', 'LTC', 'STC'))
self.assertFalse(has_errors(validate_graph(graph)))
self.assertEqual([(e['from'], e['to']) for e in graph['edges']], [('step1', 'step2'), ('step2', 'step3')])
def test_the_same_name_twice_is_told_apart(self):
graph = quick_graph(self.steps('STC', 'STC'))
self.assertEqual([step['name'] for step in graph['steps'].values()], ['STC', 'STC (2)'])
def test_a_long_name_is_cut_to_what_a_step_may_have(self):
graph = quick_graph([('x' * 100, build()[0])])
self.assertEqual(len(graph['steps']['step1']['name']), 64)
self.assertFalse(has_errors(validate_graph(graph)))
def test_each_step_has_settings_of_its_own(self):
graph = quick_graph(self.steps('STC', 'LTC'))
first, second = graph['steps']['step1']['payload'], graph['steps']['step2']['payload']
self.assertEqual((first['dev_time_control'], second['dev_time_control']), ('8.0+0.08', '40.0+0.4'))
self.assertEqual((first['dev_branch'], second['dev_branch']), ('dev', 'dev'))
def test_the_name_says_what_is_tested_and_what_runs(self):
self.assertEqual(quick_name('feature/x', ['STC', 'LTC']), 'feature/x: STC then LTC')
self.assertEqual(quick_name('feature/x', ['STC']), 'feature/x: STC')
def test_the_name_always_fits(self):
self.assertEqual(len(quick_name('b' * 255, ['STC', 'LTC'])), 128)
if __name__ == '__main__':
unittest.main()
-26
View File
@@ -1,26 +0,0 @@
# Pipeline UI (phase 2) Plan
**Goal:** Let people see their pipelines and watch a run unfold, and start, pause and cancel them from the website.
**Approach:** One pure module lays out the graph and draws it as SVG, so it can be unit tested without Django. Thin views and templates sit on top of it. The page follows the existing RektBench theme (tokens in `style.css`), and the flow graph is the one element that gets real design attention: the path a run actually took is drawn bold, everything else stays quiet.
**Stack:** Django views and templates, inline SVG, a small fetch-and-swap script for live updates.
## Decisions taken from the skills
- Every new page and action requires a login. Closed by default.
- One function, `can_manage(user, pipeline)`, decides who may start, pause, delete or cancel: the author, or an approver. Nothing else checks roles.
- Mutating routes accept POST only, carry the CSRF token, take no fields from the body, and redirect only to fixed internal paths.
- Every decision is logged as an event: who, which pipeline, allowed or denied.
- Names of steps are user text. They are escaped when the SVG is built, and the template marks only that finished string safe.
- The graph branches and loops, so steps are never numbered. The chip on a test page names the step and the pipeline.
## Tasks
1. **Layout and SVG (pure).** `OpenBench/pipeline_layout.py`, tests in `UnitTests/test_pipeline_layout.py`. Check: unit tests pass, including layering, loops, orphans and HTML escaping.
2. **Cancel a run.** `cancel_run()` in `pipelines.py`, plus keeping a cancelled run cancelled when late workloads finish. Check: new Django tests fail before, pass after.
3. **Views and permissions.** `OpenBench/pipeline_views.py`, URLs. Check: Django tests for the permission matrix (anonymous, stranger, author, approver, disabled profile) on every mutating route, and that GET never mutates.
4. **Templates, CSS, live script, navigation.** Check: pages render in the test client, the live script is served, the full suite is green.
5. **Chip on the test page.** Check: shown for a pipeline step, absent otherwise, absent when logged out.
Checkpoint after task 3: permissions are the part most worth a human look.