Compare commits

..
18 Commits
Author SHA1 Message Date
claude 7ab973ff67 Merge pull request 'Gitea sources without a token: direct archive links' (#17) from gitea-anonymous into master 2026-11-15 01:30:35 +01:00
rektdieandclaude 4bd7a68864 Gitea sources without a token: direct archive links
With REQUIRE_SIGNIN_VIEW off, public Gitea repositories can be read
anonymously, so the token is no longer required. Without one, the server
calls the Gitea API without credentials and hands workers the plain
<repo>/archive/<commit>.zip link, like Github. With a token, private
repositories still go through the signed /giteaSource/ proxy.

When a lookup fails without a token, the error says the repository must
be public.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-15 01:30:15 +01:00
claude 30032fd42d Merge pull request 'Add Rigby (MCTS engine) to the engine list' (#15) from add-rigby into master 2026-11-15 00:46:10 +01:00
claude f915c30f02 Merge pull request 'Accept engine sources from Gitea servers' (#16) from gitea-sources into master 2026-11-15 00:45:59 +01:00
rektdieandclaude 754283d95e Sign Gitea source links with the Gitea token
settings.py, SECRET_KEY included, is part of the public repository, so
links signed with it could be forged to read any repository the token can
see. The token in Config/credentials.gitea is gitignored and is now the
signing key. Without a token, Gitea tests are refused at creation and no
link validates.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-15 00:45:17 +01:00
rektdieandclaude e8cd615d83 Rigby: take sources from Gitea
Needs the Gitea source support from the gitea-sources branch.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-15 00:43:28 +01:00
rektdieandclaude c721cc6b5b Accept engine sources from Gitea servers
Tests, tunes and datagen could only use https://github.com/<user>/<repo>.
Gitea servers listed under "gitea_hosts" in Config/config.json are now
accepted too, starting with https://gitea.rektdie.com.

- OpenBench/git_hosts.py holds all host logic: repo validation, API base,
  resolving a branch/tag/sha, compare counts, diff links and source URLs.
- The server talks to Gitea with the token in Config/credentials.gitea and
  sends it nowhere else; Github requests stay unchanged.
- Gitea may require a login even to read, so workers cannot download the
  archive themselves. The server gives them a /giteaSource/ link signed with
  an HMAC of repo and commit (SECRET_KEY), and streams the archive from the
  Gitea API. No client change, no client version bump.
- Diff links, the out-of-date check and the profile page handle Gitea repos;
  the repo fields of the forms accept every configured prefix.
- Private engines stay Github-only, they depend on Github Actions artifacts.
- Static version bumped to v5 for the changed default_text.js.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-15 00:42:43 +01:00
rektdieandclaude 619d29b12e Add Rigby (MCTS engine) to the engine list
Rigby is a PUCT search engine, so its tree needs far more memory than an
alpha-beta hash: STC and LTC run with Hash=64 and Hash=256. Non-regression
presets are included for simplifications. Reference nps is calibrated
against Eleanor on the same machine (1.10M measured for 800k reference,
Rigby measures 1.08M).

The source points at a GitHub mirror, because test creation only accepts
github.com repositories.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-15 00:36:42 +01: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
21 changed files with 1897 additions and 198 deletions

No files matched your search

+6 -1
View File
@@ -8,6 +8,10 @@
"require_manual_registration" : false,
"balance_engine_throughputs" : true,
"gitea_hosts" : [
"https://gitea.rektdie.com"
],
"books" : [
"2moves_v1.epd",
"3moves_FRC.epd",
@@ -33,6 +37,7 @@
"Prelude",
"Simpler",
"Stormphrax",
"Impact"
"Impact",
"Rigby"
]
}
+78
View File
@@ -0,0 +1,78 @@
{
"private" : false,
"nps" : 780000,
"source" : "https://gitea.rektdie.com/rektdie/Rigby",
"build" : {
"path" : "",
"compilers" : ["clang++"],
"cpuflags" : [],
"systems" : ["Linux", "Windows", "Darwin"]
},
"test_presets" : {
"default" : {
"base_branch" : "main",
"book_name" : "UHO_Lichess_4852_v1.epd",
"test_bounds" : "[0.00, 5.00]",
"test_confidence" : "[0.05, 0.05]",
"win_adj" : "movecount=3 score=400",
"draw_adj" : "movenumber=40 movecount=8 score=10"
},
"STC" : {
"both_options" : "Threads=1 Hash=64",
"both_time_control" : "8.0+0.08",
"workload_size" : 32
},
"LTC" : {
"both_options" : "Threads=1 Hash=256",
"both_time_control" : "40.0+0.4",
"workload_size" : 8
},
"Non-Regression STC" : {
"test_bounds" : "[-5.00, 0.00]",
"both_options" : "Threads=1 Hash=64",
"both_time_control" : "8.0+0.08",
"workload_size" : 32
},
"Non-Regression LTC" : {
"test_bounds" : "[-5.00, 0.00]",
"both_options" : "Threads=1 Hash=256",
"both_time_control" : "40.0+0.4",
"workload_size" : 8
}
},
"tune_presets" : {
"default" : {
"book_name" : "UHO_Lichess_4852_v1.epd",
"win_adj" : "movecount=3 score=400",
"draw_adj" : "movenumber=40 movecount=8 score=10"
},
"STC" : {
"dev_options" : "Threads=1 Hash=64",
"dev_time_control" : "8.0+0.08"
},
"LTC" : {
"dev_options" : "Threads=1 Hash=256",
"dev_time_control" : "40.0+0.4"
}
},
"datagen_presets" : {
"default" : {
"win_adj" : "None",
"draw_adj" : "None",
"workload_size" : 128
}
}
}
+6 -1
View File
@@ -25,7 +25,7 @@ import traceback
from OpenSite.settings import PROJECT_PATH
OPENBENCH_STATIC_VERSION = 'v4'
OPENBENCH_STATIC_VERSION = 'v5'
OPENBENCH_CONFIG = None # Initialized by OpenBench/apps.py
@@ -101,6 +101,11 @@ def verify_general_config(conf):
assert type(conf.get("require_manual_registration") == bool)
assert type(conf.get("balance_engine_throughputs" ) == bool)
# Optional: Gitea servers that may serve engine sources, e.g. "https://gitea.example.com"
hosts = conf.get("gitea_hosts", [])
assert type(hosts) == list
assert all(type(x) == str and x.startswith('https://') and x.count('/') == 2 for x in hosts)
def verify_engine_basics(conf):
assert type(conf.get('private')) == bool
+214
View File
@@ -0,0 +1,214 @@
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
# #
# OpenBench is a chess engine testing framework authored by Andrew Grant. #
# <https://github.com/AndyGrant/OpenBench> <andrew@grantnet.us> #
# #
# OpenBench is free software: you can redistribute it and/or modify #
# it under the terms of the GNU General Public License as published by #
# the Free Software Foundation, either version 3 of the License, or #
# (at your option) any later version. #
# #
# OpenBench is distributed in the hope that it will be useful, #
# but WITHOUT ANY WARRANTY; without even the implied warranty of #
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the #
# GNU General Public License for more details. #
# #
# You should have received a copy of the GNU General Public License #
# along with this program. If not, see <http://www.gnu.org/licenses/>. #
# #
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
# Everything OpenBench needs to know about where engine sources live.
#
# Sources can be on Github, or on a Gitea server listed under "gitea_hosts" in
# Config/config.json.
#
# Workers download sources with a plain GET and no credentials. Github archives
# are public, so workers fetch them directly. For Gitea there are two modes:
#
# - Without a token, the repository must be readable anonymously (public, and
# REQUIRE_SIGNIN_VIEW off on the Gitea server). The API is called without
# credentials and workers get the plain archive link, exactly like Github.
#
# - With an API token in Config/credentials.gitea, private repositories and
# servers that require a login work too. The token is never sent to any other
# host. Workers cannot log in, so the server hands them a signed link to
# /giteaSource/, which fetches the archive with the token and passes it on.
#
# The links are signed with the Gitea token itself, not Django's SECRET_KEY:
# settings.py is part of the public repository, and a forged link would let
# anyone read every repository the token can see. Replacing the token
# invalidates the source links of tests created before.
import hashlib
import hmac
import os
import re
import urllib.parse
import requests
import OpenBench.config
from OpenSite.settings import PROJECT_PATH
GITHUB_PREFIX = 'https://github.com/'
GITHUB_PATTERN = r'^https:\/\/github\.com\/[A-Za-z0-9-]+\/[A-Za-z0-9_.-]+\/?$'
REPO_TAIL = r'\/[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+\/?$'
REQUEST_TIMEOUT = 30
def gitea_hosts():
return [host.rstrip('/') for host in OpenBench.config.OPENBENCH_CONFIG.get('gitea_hosts', [])]
def repo_prefixes():
return [GITHUB_PREFIX] + ['%s/' % (host) for host in gitea_hosts()]
def gitea_host(repo):
for host in gitea_hosts():
if repo.startswith(host + '/'):
return host
return None
def is_gitea(repo):
return gitea_host(repo) is not None
def is_valid_repo(repo):
if re.match(GITHUB_PATTERN, repo):
return True
host = gitea_host(repo)
return bool(host and re.match(REPO_TAIL, repo[len(host):]))
def owner_and_name(repo):
host = gitea_host(repo) or GITHUB_PREFIX.rstrip('/')
owner, name = repo[len(host):].strip('/').split('/')[:2]
return owner, name
def api_base(repo):
if (host := gitea_host(repo)):
return '%s/api/v1/repos/%s/%s' % ((host,) + owner_and_name(repo))
return repo.rstrip('/').replace('github.com', 'api.github.com/repos')
def read_gitea_token():
path = os.path.join(PROJECT_PATH, 'Config', 'credentials.gitea')
if os.path.exists(path):
with open(path) as fin:
return fin.readline().strip() or None
def gitea_headers():
token = read_gitea_token()
return { 'Authorization' : 'token %s' % (token) } if token else {}
def api_headers(engine, repo):
if is_gitea(repo):
return gitea_headers()
import OpenBench.utils
return OpenBench.utils.read_git_credentials(engine) or {}
def fetch_commit(repo, ref, headers):
# Returns { 'sha', 'tree', 'message' } for a branch, tag, or commit sha.
# Raises when the reference cannot be resolved.
base = api_base(repo)
bysha = bool(re.search('^[0-9a-fA-F]{40}$', ref))
if is_gitea(repo):
# One endpoint resolves branches, tags and commit shas alike
params = { 'sha' : ref, 'limit' : 1, 'stat' : 'false', 'verification' : 'false', 'files' : 'false' }
data = requests.get(base + '/commits', params=params, headers=headers, timeout=REQUEST_TIMEOUT).json()
data = data[0]
else:
# Lookup branch or commit sha, but will fail for tags
url = '%s/%s/%s' % (base, 'commits' if bysha else 'branches', ref)
data = requests.get(url, headers=headers, timeout=REQUEST_TIMEOUT).json()
# Check to see if the branch name was actually a tag name
if not bysha and 'commit' not in data:
url = '%s/commits/%s' % (base, ref)
data = requests.get(url, headers=headers, timeout=REQUEST_TIMEOUT).json()
# Actual branches have to go one layer deeper
elif not bysha: data = data['commit']
# A lookup by sha must land on exactly that commit
if bysha and data['sha'].lower() != ref.lower():
raise ValueError('%s resolved to %s' % (ref, data['sha']))
return {
'sha' : data['sha'],
'tree' : (data['commit'].get('tree') or {}).get('sha'),
'message' : data['commit']['message'],
}
def commits_ahead(repo, dev_sha, base_sha, headers):
# Number of commits on base_sha that dev_sha does not have
base = api_base(repo)
if is_gitea(repo):
url = '%s/compare/%s...%s' % (base, dev_sha, base_sha)
params = { 'verification' : 'false', 'files' : 'false' }
return int(requests.get(url, params=params, headers=headers, timeout=REQUEST_TIMEOUT).json().get('total_commits', 0))
url = '%s/compare/%s...%s' % (base, dev_sha, base_sha)
return int(requests.get(url, headers=headers, timeout=REQUEST_TIMEOUT).json().get('ahead_by', 0))
def compare_url(repo, base_sha, dev_sha):
repo = repo.rstrip('/')
if is_gitea(repo):
return '%s/compare/%s...%s' % (repo, base_sha, dev_sha)
return '%s/compare/%s..%s' % (repo, base_sha, dev_sha)
def source_signature(repo, sha):
# Without a token there is nothing secret to sign with, and nothing to fetch with
if not (key := read_gitea_token()):
return None
message = ('openbench-gitea-source\n%s\n%s' % (repo.rstrip('/'), sha.lower())).encode('utf-8')
return hmac.new(key.encode('utf-8'), message, hashlib.sha256).hexdigest()
def source_url(request, repo, commit):
# Github serves archives by tree sha, so identical trees share one download
if not is_gitea(repo):
return '%s/archive/%s.zip' % (repo.rstrip('/'), commit['tree'])
# Without a token the repository is public: workers download it directly.
# Gitea archives are addressed by commit, not by tree.
if not read_gitea_token():
return '%s/archive/%s.zip' % (repo.rstrip('/'), commit['sha'])
query = urllib.parse.urlencode({
'repo' : repo.rstrip('/'),
'sha' : commit['sha'],
'sig' : source_signature(repo, commit['sha']),
})
return request.build_absolute_uri('/giteaSource/?%s' % (query))
def verify_source_request(repo, sha, sig):
if not (is_valid_repo(repo) and is_gitea(repo) and re.match('^[0-9a-fA-F]{40}$', sha or '')):
return False
expected = source_signature(repo, sha)
return bool(expected) and hmac.compare_digest(expected, sig or '')
def open_gitea_archive(repo, sha):
# Streams the .zip for one commit from the Gitea API
url = '%s/archive/%s.zip' % (api_base(repo), sha)
response = requests.get(url, headers=gitea_headers(), stream=True, timeout=REQUEST_TIMEOUT)
response.raise_for_status()
return response
+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')
+6 -1
View File
@@ -1,5 +1,9 @@
function enforce_default_text(id, text) {
// `text` may be a list of accepted prefixes; the first one is the default.
var prefixes = Array.isArray(text) ? text : [text];
text = prefixes[0];
window.addEventListener('DOMContentLoaded', function() {
var field = document.getElementById(id);
@@ -9,7 +13,8 @@ function enforce_default_text(id, text) {
field.addEventListener('input', function() {
if (field.value.startsWith(text) || field.value === text)
// Accept any allowed prefix, and anything still being typed towards one
if (prefixes.some(function(p) { return field.value.startsWith(p) || p.startsWith(field.value); }))
return;
if (field.value.endsWith('/'))
+10 -4
View File
@@ -18,11 +18,13 @@
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 graph loads itself
var PROTECT = 'form, .banner, .llr-history-panel, [data-live-skip], script, style';
// 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 add after the page loads
var KEEP = { 'data-href': true, 'data-epoch': true };
// 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
@@ -176,6 +178,10 @@
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;
}
+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 @@
/* 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();
})();
+140 -2
View File
@@ -22,6 +22,7 @@ import html
import json
import re, django
import OpenBench.config, OpenBench.utils, OpenBench.stats, OpenBench.models
import OpenBench.git_hosts
from django.utils.safestring import mark_safe
@@ -53,14 +54,17 @@ def gitDiffLink(test):
if test.dev_engine in engines and engines[test.dev_engine]['private']:
repo = OpenBench.config.OPENBENCH_CONFIG['engines'][test.dev_engine]['source']
elif OpenBench.git_hosts.is_gitea(test.dev_repo):
repo = test.dev_repo # Gitea sources point at this server's /giteaSource/
else:
repo = OpenBench.utils.path_join(*test.dev.source.split('/')[:-2])
if test.test_mode == 'SPSA':
if OpenBench.git_hosts.is_gitea(repo):
return OpenBench.utils.path_join(repo, 'commit', test.dev.sha)
return OpenBench.utils.path_join(repo, 'compare', test.dev.sha[:8])
return OpenBench.utils.path_join(repo, 'compare',
'{0}..{1}'.format( test.base.sha[:8], test.dev.sha[:8]))
return OpenBench.git_hosts.compare_url(repo, test.base.sha[:8], test.dev.sha[:8])
def shortStatBlock(test):
@@ -544,6 +548,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 +745,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)
+6 -1
View File
@@ -18,10 +18,14 @@
# #
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
import django.urls, OpenBench.views
import django.urls, OpenBench.views, OpenBench.seo
urlpatterns = [
# Files for search engines
django.urls.path(r'robots.txt', OpenBench.seo.robots_txt),
django.urls.path(r'sitemap.xml', OpenBench.seo.sitemap_xml),
# Links for account management
django.urls.path(r'register/', OpenBench.views.register),
django.urls.path(r'login/', OpenBench.views.login),
@@ -79,6 +83,7 @@ urlpatterns = [
django.urls.path(r'clientWorkerInfo/', OpenBench.views.client_worker_info),
django.urls.path(r'clientGetWorkload/', OpenBench.views.client_get_workload),
django.urls.path(r'clientGetNetwork/<str:engine>/<str:name>/', OpenBench.views.client_get_network),
django.urls.path(r'giteaSource/', OpenBench.views.gitea_source),
django.urls.path(r'clientBenchError/', OpenBench.views.client_bench_error),
django.urls.path(r'clientSubmitNPS/', OpenBench.views.client_submit_nps),
django.urls.path(r'clientSubmitError/', OpenBench.views.client_submit_error),
+67 -8
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)
@@ -381,16 +436,12 @@ def branch_is_out_of_date(test):
if test.dev_engine != test.base_engine:
return False
# Format the request to the Github endpoint
base = 'https://api.github.com/repos/'
base = test.dev_repo.replace('github.com', 'api.github.com/repos')
url = path_join(base, 'compare', '%s...%s' % (test.dev.sha, test.base.sha))
import OpenBench.git_hosts
try:
# Out of date if ahead_by is non-zero
headers = read_git_credentials(test.dev_engine)
data = requests.get(url, headers=headers).json()
return data.get('ahead_by', 0) > 0
# Out of date if the base has commits that the dev branch lacks
headers = OpenBench.git_hosts.api_headers(test.dev_engine, test.dev_repo)
return OpenBench.git_hosts.commits_ahead(test.dev_repo, test.dev.sha, test.base.sha, headers) > 0
except:
# If something went wrong, just ignore it
@@ -575,6 +626,7 @@ def update_test(request, machine):
test = Test.objects.select_for_update().get(id=test_id)
should_record_llr = False
should_record_spsa = False
if test.finished or test.deleted:
return { 'stop' : True }
@@ -625,6 +677,7 @@ def update_test(request, machine):
param['value'] = max(param['min'], min(param['max'], x))
test.finished = test.games >= 2 * test.spsa['pairs_per'] * test.spsa['iterations']
should_record_spsa = True
elif test.test_mode == 'DATAGEN':
@@ -633,6 +686,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)
+29 -3
View File
@@ -25,6 +25,7 @@ import django.shortcuts
import django.contrib.auth
import OpenBench.config
import OpenBench.git_hosts
import OpenBench.utils
import OpenBench.uiutils
@@ -232,7 +233,10 @@ def profile_config(request):
for (engine, current_repo) in profile.repos.items():
repo_name = request.POST.get('engine-repo-%s' % (engine), '').removesuffix('/')
repo = 'https://github.com/%s' % (repo_name)
repo = repo_name if repo_name.startswith('https://') else 'https://github.com/%s' % (repo_name)
if repo_name and not OpenBench.git_hosts.is_valid_repo(repo):
return redirect(request, '/profile/', error='Repositories must be on Github or a configured Gitea server')
if repo != current_repo and repo_name:
changes += 'Updated Engine: %s to use %s\n' % (engine, repo)
@@ -246,8 +250,8 @@ def profile_config(request):
if engine_name != 'None' and engine_repo:
if not engine_repo.startswith('https://github.com/'):
return redirect(request, '/profile/', error='Repositories must be on Github')
if not OpenBench.git_hosts.is_valid_repo(engine_repo):
return redirect(request, '/profile/', error='Repositories must be on Github or a configured Gitea server')
if not profile.engine:
profile.engine = engine_name
@@ -802,6 +806,28 @@ def client_worker_info(request):
# Pass back the Machine Id, and Secret Token for this session
return JsonResponse({ 'machine_id' : machine.id, 'secret' : machine.secret })
def gitea_source(request):
# Workers download sources with a plain GET. The link carries a signature
# made at test creation, so only repo/sha pairs this server handed out work.
repo = request.GET.get('repo', '')
sha = request.GET.get('sha' , '')
sig = request.GET.get('sig' , '')
if not OpenBench.git_hosts.verify_source_request(repo, sha, sig):
return django.http.HttpResponseForbidden('Invalid source link')
try:
upstream = OpenBench.git_hosts.open_gitea_archive(repo, sha)
except Exception:
import traceback; traceback.print_exc()
return HttpResponse('Unable to fetch the source archive', status=502)
owner, name = OpenBench.git_hosts.owner_and_name(repo)
response = django.http.StreamingHttpResponse(upstream.iter_content(chunk_size=1 << 16), content_type='application/zip')
response['Content-Disposition'] = 'attachment; filename="%s-%s.zip"' % (name, sha[:8])
return response
@csrf_exempt
def client_get_network(request, engine, name):
+34 -33
View File
@@ -42,6 +42,7 @@ import requests
import traceback
import OpenBench.config
import OpenBench.git_hosts
import OpenBench.utils
from OpenBench.models import *
@@ -245,9 +246,10 @@ def verify_draw_adj(errors, request, field):
except: errors.append('Invalid Draw Adjudication Setting. Try "None"?')
def verify_github_repo(errors, request, field):
pattern = r'^https:\/\/github\.com\/[A-Za-z0-9-]+\/[A-Za-z0-9_.-]+\/?$'
try: assert re.match(pattern, request.POST[field])
except: errors.append('Sources must be found on https://github.com/<User>/<Repo>')
try: assert OpenBench.git_hosts.is_valid_repo(request.POST[field])
except:
hosts = ', '.join('%s<User>/<Repo>' % (prefix) for prefix in OpenBench.git_hosts.repo_prefixes())
errors.append('Sources must be found on %s' % (hosts))
def verify_network(errors, request, field, field_name, engine_field):
try:
@@ -353,19 +355,26 @@ def collect_github_info(errors, request, field):
# Get branch name / commit sha / tag, and the API path for it
branch = request.POST['{0}_branch'.format(field)]
bysha = bool(re.search('^[0-9a-fA-F]{40}$', branch))
# All API requests will share this common path. Some engines are private.
base = request.POST['%s_repo' % (field)].replace('github.com', 'api.github.com/repos')
repo = request.POST['%s_repo' % (field)]
base = OpenBench.git_hosts.api_base(repo)
engine = request.POST['%s_engine' % (field)]
private = OpenBench.config.OPENBENCH_CONFIG['engines'][engine]['private']
gitea = OpenBench.git_hosts.is_gitea(repo)
headers = {}
## Step 1: Verify the target of the API requests
## [A] We will not attempt to reach any site other than api.github.com
## [A] We will not attempt to reach any site other than api.github.com,
## or a Gitea server listed under "gitea_hosts" in the config
## [B] Private engines may only use their main repo for sources of tests
## [C] Determine which, if any, credentials we want to pass along
# Private engines rely on Github Actions artifacts, which Gitea does not offer
if private and gitea:
errors.append('Private engines must be hosted on Github')
return (None, None)
# Private engines must have a token stored in credentials.enginename
if private and not (headers := OpenBench.utils.read_git_credentials(engine)):
errors.append('Server does not have access tokens for this engine')
@@ -377,59 +386,51 @@ def collect_github_info(errors, request, field):
return (None, None)
# Avoid leaking our credentials to other websites
if not base.startswith('https://api.github.com/'):
errors.append('OpenBench may only reach Github\'s API')
if not OpenBench.git_hosts.is_valid_repo(repo):
errors.append('OpenBench may only reach Github\'s API or a configured Gitea server')
return (None, None)
## Step 2: Connect to the Github API for the given Branch or Commit SHA.
# Gitea servers get their own token if there is one, and nothing else.
# Without a token the repository has to be readable anonymously.
if gitea:
headers = OpenBench.git_hosts.gitea_headers()
## Step 2: Connect to the Github or Gitea API for the given Branch or Commit SHA.
## [A] We will attempt to parse the most recent commit message for a
## bench, unless one was supplied.
## [B] We will translate any branch name into a commit SHA for later use,
## so we may compare branches and generate diff URLs
## [C] If the engine is public, we will construct the URL to download the
## source code from Github into a .zip file.
## source code into a .zip file. Gitea sources go through this server.
## [D] If the engine is private, we will carry onto Step 3.
try: # Fetch data from the Github API
# Lookup branch or commit sha, but will fail for tags
url = OpenBench.utils.path_join(base, 'commits' if bysha else 'branches', branch)
data = requests.get(url, headers=headers).json()
# Check to see if the branch name was actually a tag name
if not bysha and 'commit' not in data:
url = OpenBench.utils.path_join(base, 'commits', branch)
data = requests.get(url, headers=headers).json()
# Actual branches have to go one layer deeper
elif not bysha: data = data['commit']
# Check that all the data we need going forward is present
assert 'message' in data['commit'] and 'sha' in data
assert private or 'sha' in data['commit']['tree']
try: # Resolve the branch, tag, or commit sha
commit = OpenBench.git_hosts.fetch_commit(repo, branch, headers)
assert commit['message'] is not None and commit['sha']
assert private or commit['tree']
except: # Unable to find for whatever reason
traceback.print_exc()
errors.append('%s could not be found' % (branch or 'Branch'))
hint = ' (no Gitea token on the server, so the repository must be public)' if gitea and not headers else ''
errors.append('%s could not be found%s' % (branch or 'Branch', hint))
return (None, None)
# Extract the bench from the web form, or from the commit message
if not (bench := determine_bench(request, field, data['commit']['message'])):
if not (bench := determine_bench(request, field, commit['message'])):
errors.append('Unable to parse a Bench for %s' % (branch))
return (None, None)
# Public Engines: Construct the .zip download and return everything
if not private:
treeurl = data['commit']['tree']['sha'] + '.zip'
source = OpenBench.utils.path_join(request.POST['%s_repo' % (field)], 'archive', treeurl)
return (source, branch, data['sha'], bench), True
source = OpenBench.git_hosts.source_url(request, repo, commit)
return (source, branch, commit['sha'], bench), True
## Step 3: Construct the URL for the API request to list all Artifacts
## [A] OpenBench artifacts are always run via a file named openbench.yml
## [B] These should contain combinations for windows/linux, avx2/avx512, popcnt/pext
## [C] If those artifacts are not found, we flag the test as awaiting, and try later.
url, has_all = fetch_artifact_url(base, engine, headers, data['sha'])
url, has_all = fetch_artifact_url(base, engine, headers, commit['sha'])
return (url, branch, data['sha'], bench), has_all
def requests_illegal_fork(request, field):
+15 -1
View File
@@ -27,7 +27,21 @@
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<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 %}
+2 -2
View File
@@ -15,8 +15,8 @@
document.addEventListener(
'DOMContentLoaded', function () {
change_engine('{{ profile.engine }}', 'dev', '{{workload}}');
enforce_default_text('dev_repo', 'https://github.com/');
enforce_default_text('base_repo', 'https://github.com/');
enforce_default_text('dev_repo', ['https://github.com/'{% for host in config.gitea_hosts %}, '{{host}}/'{% endfor %}]);
enforce_default_text('base_repo', ['https://github.com/'{% for host in config.gitea_hosts %}, '{{host}}/'{% endfor %}]);
}, false
);
</script>
+1 -1
View File
@@ -7,7 +7,7 @@
<script src="{% static 'default_text.js' %}?{{ static_version }}"></script>
<script>
enforce_default_text('new-engine-repo', 'https://github.com/');
enforce_default_text('new-engine-repo', ['https://github.com/'{% for host in config.gitea_hosts %}, '{{host}}/'{% endfor %}]);
</script>
{% endblock %}
+80 -10
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 %}
@@ -13,10 +17,11 @@
{% block content %}
<div class="workload-container">
<div class="workload-container{% if type == "TUNE" %} tune-page{% endif %}">
{% if type == "TUNE" %}<div class="tune-side">{% endif %}
<div id="config" class="card">
<header class="card-head"><h2 class="card-title">Configuration</h2></header>
{% if type == "TUNE" %}<details id="config" class="card config-fold"><summary><span class="card-title">Settings</span><span class="config-hint">Engine, network, book</span></summary>{% else %}<div id="config" class="card">{% endif %}
{% if type != "TUNE" %}<header class="card-head"><h2 class="card-title">Configuration</h2></header>{% endif %}
<table class="test-config left-align wrappable">
<tr><td class="td-label">Author</td><td>{{workload.author|capfirst}}</td></tr>
@@ -67,7 +72,7 @@
{% endif %}
</table>
</div>
{% if type == "TUNE" %}</details>{% else %}</div>{% endif %}
<div id="actions" class="card">
<header class="card-head"><h2 class="card-title">Actions</h2></header>
@@ -212,8 +217,72 @@
<!-- SPSA Paramater Summary, for Tunes -->
{% if type == "TUNE" %}
<div id="parameters" class="card">
<header class="card-head"><h2 class="card-title">SPSA Parameters</h2></header>
</div><!-- /tune-side -->
<div class="tune-main">
{% with panel=workload|spsa_param_panel %}
<section id="spsa-panel" class="card spsa-panel">
<header class="card-head"><h2 class="card-title">Tuning progress</h2></header>
<div class="spsa-summary">
<div class="spsa-iter">
<span class="spsa-big">{{ panel.complete }}</span>
<span class="spsa-of">of {{ panel.iterations }} iterations</span>
</div>
<div class="spsa-bar" role="progressbar" aria-label="Iterations completed" aria-valuemin="0" aria-valuemax="100" aria-valuenow="{{ panel.pct }}"><span style="width: {{ panel.pct }}%"></span></div>
<dl class="spsa-facts">
<div><dt>Parameters</dt><dd>{{ panel.count }}</dd></div>
<div><dt>Moved</dt><dd>{{ panel.moved }}</dd></div>
<div><dt>Games</dt><dd>{{ panel.games|insertCommas }}</dd></div>
</dl>
</div>
<div class="spsa-history">
<div class="spsa-history-head">
<h3>Movement since the start</h3>
<p>Each line is one parameter, as a share of its allowed range. Point at a name below to follow it, or click it to keep it on the chart.</p>
</div>
{{ workload|spsa_history_chart }}
</div>
<div class="spsa-tools">
<input id="spsa-filter" type="search" placeholder="Filter parameters" aria-label="Filter parameters by name" autocomplete="off">
<select id="spsa-sort" aria-label="Sort parameters">
<option value="index">Original order</option>
<option value="drift">Moved the most</option>
<option value="name">Name</option>
</select>
</div>
<ol id="spsa-rows" class="spsa-rows">
{% for p in panel.params %}
<li class="spsa-row{% if p.bound %} at-bound{% endif %}" data-name="{{ p.name|lower }}" data-drift="{{ p.drift }}" data-index="{{ forloop.counter0 }}">
<button type="button" class="spsa-name" aria-pressed="false" title="Show on the chart">{{ p.name }}</button>
<div class="spsa-track-wrap">
<div class="spsa-track" role="img" aria-label="{{ p.name }} is {{ p.value }}, within {{ p.min }} to {{ p.max }}, started at {{ p.start }}{% if p.bound %}, at its {{ p.bound }} limit{% endif %}" title="Start {{ p.start }}, now {{ p.value }}, C {{ p.c }}, R {{ p.r }}{% if p.bound %}. At its {{ p.bound }} limit.{% endif %}">
<span class="spsa-drift" style="left: {{ p.left }}%; width: {{ p.width }}%"></span>
<span class="spsa-start" style="left: {{ p.from }}%"></span>
<span class="spsa-now" style="left: {{ p.now }}%"></span>
</div>
<div class="spsa-scale"><span>{{ p.min }}</span><span>{{ p.max }}</span></div>
</div>
<span class="spsa-value">{{ p.value }}</span>
<span class="spsa-delta">{% if p.moved %}{{ p.delta }}{% else %}unchanged{% endif %}</span>
</li>
{% endfor %}
</ol>
<p id="spsa-empty" class="spsa-empty" hidden>No parameter matches that name.</p>
<div class="spsa-key">
<span><i class="k-start"></i>Start value</span>
<span><i class="k-now"></i>Current value</span>
<span><i class="k-limit"></i>At a limit of its range</span>
</div>
</section>
{% endwith %}
<details id="parameters" class="card config-fold">
<summary><span class="card-title">Parameter details</span><span class="config-hint">Start, limits, C and R</span></summary>
<table class="stripes wrappable">
<tr class="table-header">
@@ -234,11 +303,11 @@
</tr>
{% endfor %}
</table>
</div>
</details>
{% endif %}
<div id="results" class="card">
<header class="card-head"><h2 class="card-title">Results by Machine</h2></header>
{% if type == "TUNE" %}<details id="results" class="card config-fold"><summary><span class="card-title">Results by Machine</span><span class="config-hint">{{ results|length }} machine{{ results|length|pluralize }}, games and results</span></summary>{% else %}<div id="results" class="card">
<header class="card-head"><h2 class="card-title">Results by Machine</h2></header>{% endif %}
<table class="stripes wrappable">
<tr class="table-header">
<th>#</th>
@@ -267,7 +336,8 @@
</tr>
{% endfor %}
</table>
</div>
{% if type == "TUNE" %}</details>{% else %}</div>{% endif %}
{% if type == "TUNE" %}</div><!-- /tune-main -->{% endif %}
</div>