diff --git a/OpenBench/pipeline_graph.py b/OpenBench/pipeline_graph.py new file mode 100644 index 0000000..4b4326c --- /dev/null +++ b/OpenBench/pipeline_graph.py @@ -0,0 +1,430 @@ +# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # +# # +# OpenBench is a chess engine testing framework authored by Andrew Grant. # +# # +# # +# 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 . # +# # +# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # + + +# Pure-Python core of the Pipeline (test scheduler) feature. Nothing in here +# touches Django, the database, or the network, so that all of the decision +# making can be unit tested on its own ( see UnitTests/test_pipeline_graph.py ). +# +# A pipeline is described by a "graph", which is plain JSON: +# +# { +# "version" : 1, +# "start" : "stc", +# "max_visits" : 3, # how many times one step may run in one run +# "max_steps" : 20, # how many workloads one run may create at most +# "steps" : { +# "stc" : { "name" : "STC", "kind" : "TEST", "payload" : { ... } }, +# "ltc" : { "name" : "LTC", "kind" : "TEST", "payload" : { ... } }, +# }, +# "edges" : [ +# { "from" : "stc", "on" : "passed", "to" : "ltc" }, +# { "from" : "stc", "on" : "failed", "to" : "stc", "set" : { "test_bounds" : "[-1.00, 3.00]" } }, +# ] +# } +# +# A step payload holds the very same fields as the Create Test / Tune / Datagen +# forms do. An edge fires when its "from" step ends with the outcome "on", and +# may override some payload fields for the step that it starts ( "set" ). + +import re + +SCHEMA_VERSION = 1 + +KINDS = ('TEST', 'TUNE', 'DATAGEN') +OUTCOMES = ('passed', 'failed', 'stopped') +EDGE_CONDITIONS = OUTCOMES + ('any',) + +DEFAULT_MAX_VISITS = 3 +DEFAULT_MAX_STEPS = 20 + +LIMIT_STEPS = 30 +LIMIT_MAX_VISITS = 10 +LIMIT_MAX_STEPS = 50 + +ID_PATTERN = re.compile(r'^[A-Za-z0-9_-]{1,32}$') + +# Statuses of a StepRun that still need attention from the scheduler +ACTIVE_STATUSES = ('QUEUED', 'LAUNCHING', 'RUNNING') + +_DEV = ['dev_engine', 'dev_repo', 'dev_branch', 'dev_network', 'dev_options', 'dev_time_control'] +_BASE = ['base_engine', 'base_repo', 'base_branch', 'base_network', 'base_options', 'base_time_control'] +_GENERAL = ['book_name', 'upload_pgns', 'priority', 'throughput', 'syzygy_wdl', 'syzygy_adj', 'win_adj', 'draw_adj'] + +# Mirrors what verify_workload() and create_workload() read from the form +REQUIRED_FIELDS = { + + 'TEST' : _DEV + _BASE + _GENERAL + ['workload_size', 'test_mode'], + + 'TUNE' : _DEV + _GENERAL + [ + 'spsa_alpha', 'spsa_gamma', 'spsa_A_ratio', 'spsa_iterations', 'spsa_pairs_per', + 'spsa_reporting_type', 'spsa_distribution_type', 'spsa_inputs' ], + + 'DATAGEN' : _DEV + _BASE + _GENERAL + [ + 'workload_size', 'datagen_max_games', 'datagen_custom_genfens', 'datagen_play_reverses' ], +} + +# Fields that are only required for a given value of test_mode +CONDITIONAL_FIELDS = { + 'SPRT' : ['test_bounds', 'test_confidence'], + 'GAMES' : ['test_max_games'], +} + +OPTIONAL_FIELDS = ['dev_bench', 'base_bench'] + +ALLOWED_FIELDS = set(OPTIONAL_FIELDS) +for _fields in REQUIRED_FIELDS.values(): ALLOWED_FIELDS.update(_fields) +for _fields in CONDITIONAL_FIELDS.values(): ALLOWED_FIELDS.update(_fields) + +# Outcomes that can never happen for a kind of workload +IMPOSSIBLE_OUTCOMES = { + 'TEST' : (), + 'TUNE' : ('failed',), # A finished tune counts as passed + 'DATAGEN' : ('failed',), # A finished datagen is always passing +} + +def issue(level, code, message, step=None): + return { 'level' : level, 'code' : code, 'step' : step, 'message' : message } + +def has_errors(issues): + return any(entry['level'] == 'error' for entry in issues) + + +# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # +# VALIDATION # +# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # + +def validate_graph(graph): + + """ Returns a list of issues. Any 'error' means the graph must not be saved + or run. 'warning' and 'info' are meant to be shown, but not to block. """ + + issues = [] + + if not isinstance(graph, dict): + return [issue('error', 'graph.invalid', 'The pipeline is not a valid object')] + + if graph.get('version') != SCHEMA_VERSION: + issues.append(issue('error', 'graph.version', 'Unsupported pipeline version')) + + _validate_limits(graph, issues) + + steps = graph.get('steps') + if not isinstance(steps, dict) or not steps: + issues.append(issue('error', 'steps.empty', 'A pipeline needs at least one step')) + return issues + + if len(steps) > LIMIT_STEPS: + issues.append(issue('error', 'steps.limit', 'A pipeline may have at most %d steps' % (LIMIT_STEPS))) + + for step_id, step in steps.items(): + _validate_step(step_id, step, issues) + + if graph.get('start') not in steps: + issues.append(issue('error', 'start.missing', 'The starting step does not exist')) + + edges = graph.get('edges', []) + if not isinstance(edges, list): + issues.append(issue('error', 'edges.invalid', 'Edges must be a list')) + edges = [] + + seen = set() + for index, edge in enumerate(edges): + _validate_edge(index, edge, steps, seen, issues) + + # Structure checks only make sense on a graph that is otherwise sound + if not has_errors(issues): + _check_reachability(graph, issues) + _check_coverage(graph, issues) + _check_impossible_edges(graph, issues) + _check_loops(graph, issues) + + return issues + +def _validate_limits(graph, issues): + + for key, limit in (('max_visits', LIMIT_MAX_VISITS), ('max_steps', LIMIT_MAX_STEPS)): + value = graph.get(key) + + if value is None: + continue + + if isinstance(value, bool) or not isinstance(value, int) or not (1 <= value <= limit): + issues.append(issue('error', 'limits.%s' % (key), '%s must be an integer in [1, %d]' % (key, limit))) + +def _validate_step(step_id, step, issues): + + if not isinstance(step_id, str) or not ID_PATTERN.match(step_id): + issues.append(issue('error', 'step.id', 'Step ids may only use letters, digits, - and _ (max 32)', step_id)) + return + + if not isinstance(step, dict): + issues.append(issue('error', 'step.invalid', 'Step is not a valid object', step_id)) + return + + name = step.get('name', step_id) + if not isinstance(name, str) or not (1 <= len(name) <= 64): + issues.append(issue('error', 'step.name', 'Step names must be 1 to 64 characters', step_id)) + + kind = step.get('kind') + if kind not in KINDS: + issues.append(issue('error', 'step.kind', 'Step kind must be one of %s' % (', '.join(KINDS)), step_id)) + return + + payload = step.get('payload') + if not isinstance(payload, dict): + issues.append(issue('error', 'step.payload', 'Step has no settings', step_id)) + return + + for key, value in payload.items(): + if isinstance(value, bool) or not isinstance(value, (str, int, float)): + issues.append(issue('error', 'payload.type', 'Setting "%s" must be text or a number' % (key), step_id)) + + required = list(REQUIRED_FIELDS[kind]) + + if kind == 'TEST': + mode = str(payload.get('test_mode', '')) + if mode not in CONDITIONAL_FIELDS: + issues.append(issue('error', 'payload.test_mode', 'Test mode must be SPRT or GAMES', step_id)) + else: + required += CONDITIONAL_FIELDS[mode] + + missing = [field for field in required if field not in payload] + if missing: + issues.append(issue('error', 'payload.missing', 'Missing settings: %s' % (', '.join(missing)), step_id)) + + unknown = [key for key in payload if key not in ALLOWED_FIELDS] + if unknown: + issues.append(issue('warning', 'payload.unknown', 'Unknown settings are ignored: %s' % (', '.join(unknown)), step_id)) + +def _validate_edge(index, edge, steps, seen, issues): + + if not isinstance(edge, dict): + issues.append(issue('error', 'edge.invalid', 'Edge #%d is not a valid object' % (index + 1))) + return + + source, target, cond = edge.get('from'), edge.get('to'), edge.get('on') + + if source not in steps: + issues.append(issue('error', 'edge.from', 'Edge #%d starts at an unknown step' % (index + 1))) + + if target is not None and target not in steps: + issues.append(issue('error', 'edge.to', 'Edge #%d leads to an unknown step' % (index + 1), source)) + + if cond not in EDGE_CONDITIONS: + issues.append(issue('error', 'edge.on', 'Edge #%d needs a condition: %s' % (index + 1, ', '.join(EDGE_CONDITIONS)), source)) + + overrides = edge.get('set', {}) + if not isinstance(overrides, dict): + issues.append(issue('error', 'edge.set', 'Edge #%d has invalid overrides' % (index + 1), source)) + overrides = {} + + for key, value in overrides.items(): + if key not in ALLOWED_FIELDS: + issues.append(issue('error', 'edge.set.key', 'Edge #%d overrides unknown setting "%s"' % (index + 1, key), source)) + if isinstance(value, bool) or not isinstance(value, (str, int, float)): + issues.append(issue('error', 'edge.set.type', 'Edge #%d: "%s" must be text or a number' % (index + 1, key), source)) + + try: + signature = (source, cond, target, tuple(sorted((k, str(v)) for k, v in overrides.items()))) + if signature in seen: + issues.append(issue('error', 'edge.duplicate', 'Edge #%d duplicates an earlier edge' % (index + 1), source)) + seen.add(signature) + except TypeError: + pass # Unhashable garbage was already reported above + +def _successors(graph): + + result = { step_id : [] for step_id in graph['steps'] } + for edge in graph.get('edges', []): + if edge['to'] is not None: + result[edge['from']].append(edge['to']) + return result + +def _check_reachability(graph, issues): + + successors = _successors(graph) + reached, stack = set(), [graph['start']] + + while stack: + step_id = stack.pop() + if step_id in reached: continue + reached.add(step_id) + stack.extend(successors[step_id]) + + for step_id in graph['steps']: + if step_id not in reached: + issues.append(issue('warning', 'step.unreachable', 'This step can never start', step_id)) + +def _check_coverage(graph, issues): + + outgoing = {} + for edge in graph.get('edges', []): + outgoing.setdefault(edge['from'], set()).add(edge['on']) + + for step_id, step in graph['steps'].items(): + + conditions = outgoing.get(step_id) + if not conditions or 'any' in conditions: + continue # Terminal steps, or steps that always continue + + possible = [o for o in OUTCOMES if o not in IMPOSSIBLE_OUTCOMES[step['kind']]] + for outcome in possible: + if outcome not in conditions: + issues.append(issue('info', 'branch.uncovered', 'If this ends %s, the pipeline stops here' % (outcome), step_id)) + +def _check_impossible_edges(graph, issues): + + for edge in graph.get('edges', []): + kind = graph['steps'][edge['from']]['kind'] + if edge['on'] in IMPOSSIBLE_OUTCOMES[kind]: + issues.append(issue('warning', 'edge.impossible', 'A %s can never end as %s, so this edge never fires' % (kind.lower(), edge['on']), edge['from'])) + +def _check_loops(graph, issues): + + successors = _successors(graph) + limit = graph.get('max_visits', DEFAULT_MAX_VISITS) + state = {} # 1 = on the current path, 2 = finished + reported = set() + + def visit(step_id): + state[step_id] = 1 + for target in successors[step_id]: + if state.get(target) == 1 and (step_id, target) not in reported: + reported.add((step_id, target)) + issues.append(issue('warning', 'loop', 'Loop back to "%s", capped at %d runs per step' % (target, limit), step_id)) + elif target not in state: + visit(target) + state[step_id] = 2 + + visit(graph['start']) + + +# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # +# EXECUTION # +# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # + +class Fire(object): + + """ A workload that the scheduler has decided to create """ + + def __init__(self, step_key, kind, payload, via=''): + self.step_key = step_key + self.kind = kind + self.payload = payload + self.via = via # The outcome that led here, or '' for the start + + def __repr__(self): + return 'Fire(%s, %s, via=%r)' % (self.step_key, self.kind, self.via) + +class Plan(object): + + def __init__(self): + self.fires = [] # Fire objects, to create + self.notes = [] # Human readable reasons for anything skipped + +def build_payload(step, overrides=None): + + """ Final form fields for a step, as strings, exactly like a form post """ + + payload = dict(step['payload']) + payload.update(overrides or {}) + return { str(key) : str(value) for key, value in payload.items() } + +def initial_fire(graph): + + start = graph['start'] + step = graph['steps'][start] + return Fire(start, step['kind'], build_payload(step)) + +def plan_next(graph, step_key, outcome, visits, fired): + + """ Decide what follows a step that just ended with the given outcome. + + visits : { step_key : how many times that step was already created } + fired : how many workloads this run has already created in total """ + + assert outcome in OUTCOMES + + max_visits = graph.get('max_visits', DEFAULT_MAX_VISITS) + max_steps = graph.get('max_steps' , DEFAULT_MAX_STEPS ) + + plan, planned = Plan(), {} + + matching = [ + edge for edge in graph.get('edges', []) + if edge['from'] == step_key and edge['on'] in (outcome, 'any') + ] + + if not matching: + plan.notes.append('Pipeline ended after "%s" (%s): no edge for this outcome' % (step_key, outcome)) + + for edge in matching: + + target = edge['to'] + if target is None: + plan.notes.append('Pipeline ended after "%s" (%s)' % (step_key, outcome)) + continue + + if target in planned: + plan.notes.append('"%s" was already queued by another edge' % (target)) + continue + + if fired + len(plan.fires) >= max_steps: + plan.notes.append('Not starting "%s": reached the limit of %d workloads' % (target, max_steps)) + continue + + if visits.get(target, 0) >= max_visits: + plan.notes.append('Not starting "%s": reached the limit of %d runs' % (target, max_visits)) + continue + + step = graph['steps'][target] + plan.fires.append(Fire(target, step['kind'], build_payload(step, edge.get('set')), outcome)) + planned[target] = True + + return plan + +def classify_outcome(finished, deleted, passed, failed, test_mode, games, spsa=None): + + """ One of OUTCOMES for a workload that is over, or None while it is not """ + + if finished: + + if passed: return 'passed' + if failed: return 'failed' + + # A tune never passes or fails. Running all of its iterations is success + if test_mode == 'SPSA' and spsa: + target = 2 * spsa.get('pairs_per', 0) * spsa.get('iterations', 0) + if target > 0 and games >= target: + return 'passed' + + return 'stopped' # Stopped by hand, or by a bad bench + + return 'stopped' if deleted else None + +def run_status(statuses): + + """ RUNNING while anything is in flight, else ERROR if anything could not + be created, else COMPLETED """ + + if any(status in ACTIVE_STATUSES for status in statuses): return 'RUNNING' + if any(status == 'ERROR' for status in statuses): return 'ERROR' + return 'COMPLETED'