554 lines
38 KiB
Python

#!/usr/bin/env python3
"""Trusted parent oracle; candidate implementation executes only as a child observer."""
import copy
import json
from pathlib import Path
import random
import subprocess
import sys
import tempfile
CANDIDATES = ('hierarchical_fsm.hpp', 'chart_model.cpp', 'dispatch_step.cpp', 'dispatch_batch.cpp')
SOURCES = ('chart_model.cpp', 'dispatch_step.cpp', 'dispatch_batch.cpp')
CONTEXT = {'fsm_observe.cpp': '#include "hierarchical_fsm.hpp"\n#include <charconv>\n#include <iostream>\n#include <sstream>\n#include <string>\n#include <utility>\n#include <vector>\n\nnamespace {\nusing namespace hierarchical_fsm;\n\nclass Fields {\npublic:\n explicit Fields(const std::string &line)\n {\n std::istringstream stream(line);\n std::string token;\n while (stream >> token) words_.push_back(token);\n }\n bool empty() const { return words_.empty(); }\n const std::string &head() const { return words_.front(); }\n template<class Number> bool number(Number &value)\n {\n if (position_ == words_.size()) return false;\n const std::string &token = words_[position_++];\n const auto result = std::from_chars(token.data(), token.data() + token.size(), value);\n return result.ec == std::errc{} && result.ptr == token.data() + token.size();\n }\n bool done() const { return position_ == words_.size(); }\nprivate:\n std::vector<std::string> words_;\n std::size_t position_ = 1;\n};\n\ntemplate<class T, class Printer>\nvoid list(std::ostream &stream, const std::vector<T> &values, Printer print)\n{\n stream << \'[\';\n for (std::size_t i = 0; i < values.size(); ++i) {\n if (i != 0) stream << \',\';\n print(stream, values[i]);\n }\n stream << \']\';\n}\n\nvoid ids(std::ostream &stream, const std::vector<StateId> &values)\n{\n list(stream, values, [](std::ostream &out, StateId id) { out << id; });\n}\n\nvoid state(std::ostream &stream, const State &value)\n{\n stream << \'[\' << value.id << \',\' << value.parent << \',\' << value.initial\n << \',\' << value.enter_tag << \',\' << value.leave_tag << \']\';\n}\n\nvoid transition(std::ostream &stream, const Transition &value)\n{\n stream << \'[\' << value.id << \',\' << value.source << \',\' << value.event\n << \',\' << value.required << \',\' << value.forbidden << \',\' << value.priority\n << \',\' << value.kind << \',\' << value.target << \',\' << value.target_mode\n << \',\' << value.action_tag << \']\';\n}\n\nvoid chart(std::ostream &stream, const Chart &value)\n{\n stream << \'[\' << value.root << \',\';\n list(stream, value.states, state);\n stream << \',\';\n list(stream, value.transitions, transition);\n stream << \']\';\n}\n\nvoid analysis(std::ostream &stream, const Analysis &value)\n{\n stream << \'[\';\n list(stream, value.states, [](std::ostream &out, const StateInfo &info) {\n out << \'[\';\n state(out, info.state);\n out << \',\';\n ids(out, info.path);\n out << \',\';\n ids(out, info.children);\n out << \',\' << info.initial_leaf << \']\';\n });\n stream << \',\';\n list(stream, value.transitions, transition);\n stream << \']\';\n}\n\nvoid snapshot(std::ostream &stream, const Snapshot &value)\n{\n stream << \'[\' << (value.configured ? "true" : "false") << \',\' << value.root << \',\';\n ids(stream, value.active);\n stream << \',\';\n list(stream, value.history, [](std::ostream &out, const Memory &memory) {\n out << \'[\' << memory.composite << \',\' << memory.child << \']\';\n });\n stream << \']\';\n}\n\nvoid record(std::ostream &stream, const Record &value)\n{\n stream << \'[\' << static_cast<std::uint32_t>(value.phase)\n << \',\' << value.state << \',\' << value.tag << \']\';\n}\n\nvoid selection(std::ostream &stream, const Selection &value)\n{\n stream << \'[\' << (value.found ? "true" : "false") << \',\';\n transition(stream, value.transition);\n stream << \']\';\n}\n\nvoid step(std::ostream &stream, const Step &value)\n{\n stream << \'[\';\n selection(stream, value.selected);\n stream << \',\' << value.boundary << \',\';\n list(stream, value.trace, record);\n stream << \']\';\n}\n\nvoid event(std::ostream &stream, const RawEvent &value)\n{\n stream << \'[\' << value.event << \',\' << value.flags << \']\';\n}\n\ntemplate<class T, class Printer>\nstd::string capture(const T &value, Printer print)\n{\n std::ostringstream stream;\n print(stream, value);\n return stream.str();\n}\n\nSelection dirty_selection()\n{\n Selection output;\n output.found = true;\n output.transition = Transition{60000, 60001, 250, 7, 9, -17, 1, 60002, 1, 60003};\n return output;\n}\n\nStep dirty_step()\n{\n return Step{dirty_selection(), 60004, {{Phase::action, 60005, 60006}}};\n}\n\nbool next_payload(const char *required, Fields &fields)\n{\n std::string line;\n if (!std::getline(std::cin, line)) return false;\n fields = Fields(line);\n return !fields.empty() && fields.head() == required;\n}\n\nbool read_chart(Fields &fields, Chart &output)\n{\n std::uint32_t count_states = 0;\n std::uint32_t count_transitions = 0;\n Chart replacement;\n if (!fields.number(replacement.root) || !fields.number(count_states) ||\n !fields.number(count_transitions) || !fields.done() ||\n count_states > 65 || count_transitions > 513) return false;\n for (std::uint32_t i = 0; i < count_states; ++i) {\n Fields row("");\n State value;\n if (!next_payload("N", row) || !row.number(value.id) ||\n !row.number(value.parent) || !row.number(value.initial) ||\n !row.number(value.enter_tag) || !row.number(value.leave_tag) ||\n !row.done()) return false;\n replacement.states.push_back(value);\n }\n for (std::uint32_t i = 0; i < count_transitions; ++i) {\n Fields row("");\n Transition value;\n if (!next_payload("T", row) || !row.number(value.id) ||\n !row.number(value.source) || !row.number(value.event) ||\n !row.number(value.required) || !row.number(value.forbidden) ||\n !row.number(value.priority) || !row.number(value.kind) ||\n !row.number(value.target) || !row.number(value.target_mode) ||\n !row.number(value.action_tag) || !row.done()) return false;\n replacement.transitions.push_back(value);\n }\n output = std::move(replacement);\n return true;\n}\n\nint protocol_error()\n{\n std::cerr << "invalid observation command\\n";\n return 2;\n}\n}\n\nint main()\n{\n using namespace hierarchical_fsm;\n Machine machines[2];\n Snapshot saved[4];\n Chart input;\n unsigned bank = 0;\n std::string line;\n std::cout << std::boolalpha;\n while (std::getline(std::cin, line)) {\n Fields fields(line);\n if (fields.empty() || fields.head()[0] == \'#\') continue;\n const std::string op = fields.head();\n Machine &machine = machines[bank];\n if (op == "C") {\n if (!read_chart(fields, input)) return protocol_error();\n std::cout << "[\\"C\\"]\\n";\n } else if (op == "U") {\n unsigned selected = 0;\n if (!fields.number(selected) || !fields.done() || selected > 1) return protocol_error();\n bank = selected;\n std::cout << "[\\"U\\"," << bank << "]\\n";\n } else if (op == "Y") {\n unsigned destination = 0;\n if (!fields.number(destination) || !fields.done() || destination > 1) return protocol_error();\n Snapshot before = machine.snapshot();\n const std::string before_text = capture(before, snapshot);\n Machine copy(machine);\n machines[destination] = copy;\n std::cout << "[\\"Y\\"," << destination << \',\' << before_text << \',\';\n snapshot(std::cout, machines[destination].snapshot());\n std::cout << \',\' << (before_text == capture(before, snapshot)) << "]\\n";\n } else if (op == "V" || op == "A") {\n if (!fields.done()) return protocol_error();\n const std::string raw_before = capture(input, chart);\n Analysis output{{StateInfo{State{60000, 0, 0, 1, 2}, {60000}, {60001}, 60002}},\n {dirty_selection().transition}};\n const Status status = op == "V" ? validate_chart(input) : analyze_chart(input, output);\n std::cout << "[\\"" << op << "\\"," << static_cast<int>(status);\n if (op == "A") { std::cout << \',\'; analysis(std::cout, output); }\n std::cout << \',\' << (raw_before == capture(input, chart)) << "]\\n";\n } else if (op == "R") {\n if (!fields.done()) return protocol_error();\n Snapshot before = machine.snapshot();\n const std::string before_text = capture(before, snapshot);\n const std::string raw_before = capture(input, chart);\n std::vector<Record> output{{Phase::action, 60000, 60001}};\n const Status status = machine.reset(input, output);\n std::cout << "[\\"R\\"," << static_cast<int>(status) << \',\' << before_text << \',\';\n snapshot(std::cout, machine.snapshot());\n std::cout << \',\';\n list(std::cout, output, record);\n std::cout << \',\' << (raw_before == capture(input, chart))\n << \',\' << (before_text == capture(before, snapshot)) << "]\\n";\n } else if (op == "Q" || op == "D") {\n RawEvent raw;\n if (!fields.number(raw.event) || !fields.number(raw.flags) || !fields.done()) return protocol_error();\n const std::string raw_before = capture(raw, event);\n Snapshot before = machine.snapshot();\n const std::string before_text = capture(before, snapshot);\n Selection selected = dirty_selection();\n Step output = dirty_step();\n const Status status = op == "Q" ? machine.select(raw, selected) : machine.dispatch(raw, output);\n std::cout << "[\\"" << op << "\\"," << static_cast<int>(status) << \',\' << before_text << \',\';\n snapshot(std::cout, machine.snapshot());\n std::cout << \',\';\n if (op == "Q") selection(std::cout, selected); else step(std::cout, output);\n std::cout << \',\' << (raw_before == capture(raw, event))\n << \',\' << (before_text == capture(before, snapshot)) << "]\\n";\n } else if (op == "B") {\n unsigned count = 0;\n if (!fields.number(count) || !fields.done() || count > 129) return protocol_error();\n std::vector<RawEvent> events;\n for (unsigned i = 0; i < count; ++i) {\n Fields row("");\n RawEvent raw;\n if (!next_payload("E", row) || !row.number(raw.event) ||\n !row.number(raw.flags) || !row.done()) return protocol_error();\n events.push_back(raw);\n }\n const auto raw_text = [](std::ostream &out, const std::vector<RawEvent> &raw) {\n list(out, raw, event);\n };\n const std::string raw_before = capture(events, raw_text);\n Snapshot before = machine.snapshot();\n const std::string before_text = capture(before, snapshot);\n std::vector<Step> output{dirty_step()};\n const Status status = machine.dispatch_many(events, output);\n std::cout << "[\\"B\\"," << static_cast<int>(status) << \',\' << before_text << \',\';\n snapshot(std::cout, machine.snapshot());\n std::cout << \',\';\n list(std::cout, output, step);\n std::cout << \',\' << (raw_before == capture(events, raw_text))\n << \',\' << (before_text == capture(before, snapshot)) << "]\\n";\n } else if (op == "P" || op == "K" || op == "O") {\n unsigned slot = 0;\n if (op != "P" && (!fields.number(slot) || slot > 3)) return protocol_error();\n if (!fields.done()) return protocol_error();\n if (op == "K") saved[slot] = machine.snapshot();\n std::cout << "[\\"" << op << "\\",";\n if (op == "P") snapshot(std::cout, machine.snapshot());\n else { std::cout << slot << \',\'; snapshot(std::cout, saved[slot]); }\n std::cout << "]\\n";\n } else {\n return protocol_error();\n }\n }\n if (std::cin.bad()) return protocol_error();\n return 0;\n}\n'}
MASK = (1 << 32) - 1
EMPTY_TRANSITION = [0] * 10
EMPTY_SELECTION = [False, EMPTY_TRANSITION]
EMPTY_STEP = [EMPTY_SELECTION, 0, []]
EMPTY_SNAPSHOT = [False, 0, [], []]
def valid_chart(chart):
root, states, transitions = chart
if not 1 <= len(states) <= 64 or len(transitions) > 512 or not 1 <= root <= 65535:
return False
table = {}
for state in states:
ident, parent, initial, enter, leave = state
if (not 1 <= ident <= 65535 or ident in table or not 0 <= parent <= 65535 or
not 0 <= initial <= 65535 or not 0 <= enter <= 65535 or not 0 <= leave <= 65535):
return False
table[ident] = state
if root not in table:
return False
children = {ident: [] for ident in table}
for ident, parent, initial, enter, leave in states:
if parent == 0:
if ident != root:
return False
else:
if ident == root or parent not in table or parent == ident:
return False
children[parent].append(ident)
for ident, parent, initial, enter, leave in states:
visited = set()
current = ident
while current:
if current in visited or current not in table:
return False
visited.add(current)
current = table[current][1]
if root not in visited:
return False
if children[ident]:
if initial not in children[ident]:
return False
elif initial != 0:
return False
ids = set()
counts = dict.fromkeys(table, 0)
for ident, source, event, required, forbidden, priority, kind, target, mode, tag in transitions:
if (not 1 <= ident <= 65535 or ident in ids or source not in table or
not 0 <= event <= 255 or not 0 <= required <= MASK or
not 0 <= forbidden <= MASK or not -(1 << 31) <= priority < (1 << 31) or
not 0 <= tag <= 65535 or kind not in (0, 1)):
return False
ids.add(ident)
counts[source] += 1
if counts[source] > 8:
return False
if kind == 0:
if target != 0 or mode != 0:
return False
elif target not in table or mode not in (0, 1) or (mode == 1 and not children[target]):
return False
return True
def analyze(chart):
if not valid_chart(chart):
return -22, [[], []]
root, states, transitions = chart
table = {s[0]: s for s in states}
output = []
for ident in sorted(table):
chain, current = [], ident
while current:
chain.insert(0, current)
current = table[current][1]
leaf = ident
while table[leaf][2]:
leaf = table[leaf][2]
children = sorted(s[0] for s in states if s[1] == ident)
output.append([copy.deepcopy(table[ident]), chain, children, leaf])
ordered = sorted(transitions, key=lambda t: (t[1], t[2], -t[5], t[0]))
return 0, [output, copy.deepcopy(ordered)]
class Model:
def __init__(self):
self.chart = None
self.active = []
self.memory = {}
def view(self):
if self.chart is None:
return copy.deepcopy(EMPTY_SNAPSHOT)
return [True, self.chart[0], list(self.active), [[p, self.memory[p]] for p in sorted(self.memory)]]
def reset(self, chart):
if not valid_chart(chart):
return -22, []
self.chart = copy.deepcopy(chart)
self.active = []
self.memory = {}
table = {s[0]: s for s in chart[1]}
current, trace = chart[0], []
while current:
self.active.append(current)
trace.append([2, current, table[current][3]])
current = table[current][2]
return 0, trace
def select(self, event):
if self.chart is None:
return -19, copy.deepcopy(EMPTY_SELECTION)
code, flags = event
if not 0 <= code <= 255 or not 0 <= flags <= MASK:
return -22, copy.deepcopy(EMPTY_SELECTION)
for source in reversed(self.active):
enabled = [t for t in self.chart[2] if t[1] == source and t[2] == code and
flags & t[3] == t[3] and flags & t[4] == 0]
if enabled:
winner = min(enabled, key=lambda t: (-t[5], t[0]))
return 0, [True, copy.deepcopy(winner)]
return 0, copy.deepcopy(EMPTY_SELECTION)
def dispatch(self, event):
status, selection = self.select(event)
if status or not selection[0]:
return status, copy.deepcopy(EMPTY_STEP)
rule = selection[1]
source, kind, target, mode, tag = rule[1], rule[6], rule[7], rule[8], rule[9]
if kind == 0:
return 0, [selection, 0, [[1, source, tag]]]
table = {s[0]: s for s in self.chart[1]}
ancestors = set()
current = source
while current:
ancestors.add(current)
current = table[current][1]
common = target
while common not in ancestors:
common = table[common][1]
boundary = table[source][1] if common == source else common
trace, child = [], 0
while self.active and self.active[-1] != boundary:
leaving = self.active.pop()
if table[leaving][2]:
self.memory[leaving] = child
trace.append([0, leaving, table[leaving][4]])
child = leaving
trace.append([1, source, tag])
entering, current = [], target
while current != boundary:
entering.insert(0, current)
current = table[current][1]
for current in entering:
self.active.append(current)
trace.append([2, current, table[current][3]])
current = self.memory.get(target, table[target][2]) if mode == 1 else table[target][2]
while current:
self.active.append(current)
trace.append([2, current, table[current][3]])
current = table[current][2]
return 0, [selection, boundary, trace]
def many(self, events):
if self.chart is None:
return -19, []
if len(events) > 128:
return -22, []
before = copy.deepcopy(self.__dict__)
output = []
for event in events:
status, step = self.dispatch(event)
if status:
self.__dict__ = before
return status, []
output.append(step)
return 0, output
class Observations:
def __init__(self):
self.commands = []
self.expected = []
self.labels = []
self.inputs = []
self.chart = [0, [], []]
self.models = [Model(), Model()]
self.bank = 0
self.saved = [copy.deepcopy(EMPTY_SNAPSHOT) for _ in range(4)]
def emit(self, command, expected, label, clauses):
self.commands.append(command)
self.expected.append(copy.deepcopy(expected))
self.labels.append((label, tuple(clauses)))
self.inputs.append({'command': command, 'command_index': len(self.commands) - 1,
'chart': copy.deepcopy(self.chart), 'bank': self.bank})
def load(self, chart, label='raw-chart'):
self.chart = copy.deepcopy(chart)
root, states, transitions = chart
rows = ['C %d %d %d' % (root, len(states), len(transitions))]
rows += ['N ' + ' '.join(map(str, s)) for s in states]
rows += ['T ' + ' '.join(map(str, t)) for t in transitions]
self.emit('\n'.join(rows), ['C'], label, ['H38'])
def call(self, command, label, clauses):
fields = command.split()
op = fields[0]
model = self.models[self.bank]
before = model.view()
if op == 'U':
self.bank = int(fields[1])
expected = ['U', self.bank]
elif op == 'Y':
destination = int(fields[1])
self.models[destination] = copy.deepcopy(model)
expected = ['Y', destination, before, self.models[destination].view(), True]
elif op == 'V':
expected = ['V', 0 if valid_chart(self.chart) else -22, True]
elif op == 'A':
status, result = analyze(self.chart)
expected = ['A', status, result, True]
elif op == 'R':
status, trace = model.reset(self.chart)
expected = ['R', status, before, model.view(), trace, True, True]
elif op in ('Q', 'D'):
event = list(map(int, fields[1:]))
status, result = model.select(event) if op == 'Q' else model.dispatch(event)
expected = [op, status, before, model.view(), result, True, True]
elif op == 'P':
expected = ['P', before]
elif op == 'K':
slot = int(fields[1])
self.saved[slot] = before
expected = ['K', slot, before]
elif op == 'O':
slot = int(fields[1])
expected = ['O', slot, self.saved[slot]]
else:
raise AssertionError(command)
self.emit(command, expected, label, clauses)
def batch(self, events, label, clauses=('H08', 'H14', 'H27', 'H28', 'H29', 'H38')):
model = self.models[self.bank]
before = model.view()
status, output = model.many(events)
command = 'B %d' % len(events)
command += ''.join('\nE %d %d' % tuple(event) for event in events)
self.emit(command, ['B', status, before, model.view(), output, True, True], label, clauses)
def inspect(self, chart, label, clauses=('H01', 'H02', 'H03', 'H04', 'H05', 'H06', 'H07', 'H09', 'H10', 'H12', 'H29')):
self.load(chart, label + '/raw')
for command in ('V', 'A', 'R', 'P'):
self.call(command, label + '/' + command, clauses)
def state(ident, parent=0, initial=0, enter=None, leave=None):
return [ident, parent, initial, ident % 65536 if enter is None else enter,
(ident * 3) % 65536 if leave is None else leave]
def transition(ident, source, event=7, required=0, forbidden=0, priority=0,
kind=0, target=0, mode=0, tag=None):
return [ident, source, event, required, forbidden, priority, kind, target, mode,
ident if tag is None else tag]
def small_chart():
return [1, [state(1, 0, 2), state(2, 1), state(3, 1)],
[transition(1, 2, 1, kind=1, target=3), transition(2, 3, 2, kind=1, target=2)]]
def history_chart():
return [10, [state(10, 0, 20), state(20, 10, 30), state(30, 20, 40),
state(40, 30), state(50, 30), state(60, 10)],
[transition(1, 40, 1, kind=1, target=50),
transition(2, 20, 2, kind=1, target=60),
transition(3, 60, 3, kind=1, target=20, mode=1),
transition(4, 20, 4, kind=1, target=20, mode=1),
transition(5, 30, 5, kind=1, target=20),
transition(6, 10, 6, kind=1, target=10),
transition(7, 60, 7, kind=1, target=20)]]
def plan():
obs = Observations()
c = obs.call
for command in ('V', 'A', 'R', 'P', 'Q 256 18446744073709551615',
'D 256 4294967296', 'K 0', 'O 1', 'Y 1'):
c(command, 'default-and-empty-domain', ['H02', 'H09', 'H10', 'H11', 'H12', 'H13', 'H14', 'H29', 'H38'])
obs.batch([], 'default-empty-batch')
obs.batch([[256, 0]] * 129, 'default-priority-before-length')
field = [1, [state(1, 0, 2, 10, 11), state(2, 1, 3, 20, 21), state(3, 2, 0, 30, 31)],
[transition(10, 2, priority=100, tag=900), transition(11, 3, priority=-5, tag=901)]]
obs.inspect(field, 'field-and-full-analysis')
for command in ('Q 7 0', 'D 7 0', 'P'):
c(command, 'isolated-A-leaf-before-ancestor', ['H15', 'H16', 'H17', 'H18', 'H26', 'H31'])
leaf_self = [1, [state(1, 0, 2), state(2, 1)], [transition(1, 2, kind=1, target=2)]]
obs.inspect(leaf_self, 'leaf-self-setup')
c('D 7 0', 'isolated-B-leaf-external-self', ['H19', 'H20', 'H23', 'H25', 'H26', 'H32'])
obs.inspect(history_chart(), 'history-setup')
for event in (1, 2, 3):
c('D %d 0' % event, 'isolated-C-shallow-direct-child-%d' % event,
['H21', 'H22', 'H24', 'H25', 'H26', 'H33'])
c('P', 'isolated-C-stored-history-persists', ['H13', 'H21', 'H24', 'H33'])
for event in (1, 4, 2, 7, 1, 5, 6):
c('D %d 0' % event, 'external-history-write-read-and-root-%d' % event,
['H19', 'H20', 'H21', 'H22', 'H23', 'H24', 'H25', 'H32', 'H34'])
c('K 0', 'held-hierarchical-snapshot', ['H13', 'H29', 'H30'])
c('R', 'reset-clears-history', ['H12', 'H13', 'H34'])
c('O 0', 'old-snapshot-after-reset', ['H13', 'H29', 'H30'])
changed_child = [1, [state(1, 0, 2), state(2, 1, 3), state(3, 2, 4),
state(4, 3), state(5, 3), state(6, 2, 7),
state(7, 6), state(8, 6), state(9, 1)],
[transition(1, 4, 1, kind=1, target=5),
transition(2, 2, 2, kind=1, target=9),
transition(3, 9, 3, kind=1, target=8),
transition(4, 2, 4, kind=1, target=2, mode=1),
transition(5, 2, 5, kind=1, target=2),
transition(6, 4, 6, kind=1, target=2),
transition(7, 4, 7, kind=1, target=2, mode=1),
transition(9, 9, 9, kind=1, target=2, mode=1)]]
obs.inspect(changed_child, 'distinct-history-child-setup')
for event in (1, 2, 3, 4):
c('D %d 0' % event, 'history-self-writes-new-child-before-read-%d' % event,
['H19', 'H20', 'H21', 'H22', 'H23', 'H24', 'H25', 'H26', 'H34'])
c('P', 'history-self-new-child-not-stale-child', ['H13', 'H21', 'H22', 'H24', 'H34'])
for event in (5, 6, 7):
c('D %d 0' % event, 'boundary-history-preserved-%d' % event,
['H19', 'H20', 'H21', 'H22', 'H23', 'H24', 'H25', 'H26', 'H34'])
no_saved_child = copy.deepcopy(changed_child)
no_saved_child[1][0][2] = 9
obs.inspect(no_saved_child, 'unsaved-history-target-setup')
c('D 9 0', 'unsaved-history-falls-back-to-initial', ['H22', 'H24', 'H25', 'H26', 'H34'])
obs.inspect(small_chart(), 'batch-setup')
obs.batch([[1, 0], [256, 0]], 'isolated-D-late-invalid-event')
c('P', 'isolated-D-state-kept', ['H26', 'H27', 'H28'])
obs.batch([[1, 0]], 'legal-prefix-independent-of-later-invalid')
obs.batch([], 'configured-empty-batch')
for raw in ([256, 0], [MASK, 0], [1, MASK + 1], [1, (1 << 64) - 1]):
for op in ('Q', 'D'):
c('%s %d %d' % (op, raw[0], raw[1]), 'raw-event-wide-rejected', ['H08', 'H14', 'H17', 'H26', 'H38'])
obs.batch([[2, 0], [1, MASK + 1]], 'late-invalid-wide-flags')
obs.batch([[0, 0]] * 129, 'overlength-batch-atomic')
c('Y 1', 'copy-construction-assignment', ['H11', 'H29', 'H30'])
c('D 2 0', 'source-copy-diverges', ['H11', 'H26', 'H29', 'H30'])
c('U 1', 'select-copied-bank', ['H11', 'H29', 'H30'])
c('P', 'copy-old-active-kept', ['H11', 'H29', 'H30'])
c('D 2 0', 'copy-independent-transition', ['H11', 'H26', 'H29', 'H30'])
c('U 0', 'return-source-bank', ['H11', 'H29', 'H30'])
c('P', 'source-not-backmodified', ['H11', 'H29', 'H30'])
# Single-error graph variants, including errors off the initial/active branch.
base = history_chart()
bad = []
def changed(label, section, row, column, value):
chart = copy.deepcopy(base)
chart[section][row][column] = value
bad.append((label, chart))
bad.append(('empty-chart', [0, [], []]))
bad.append(('off-initial-reverse-ancestor-missing-parent',
[1, [state(1, 0, 4, 0, 0), state(2, 3, 0, 0, 0),
state(3, 999, 2, 0, 0), state(4, 1, 0, 0, 0)], []]))
for root in (0, 65536, 65535):
chart = copy.deepcopy(base)
chart[0] = root
bad.append(('bad-root-%d' % root, chart))
for col, values in ((0, [0, 65536, 10]), (1, [0, 60, 65536, MASK]),
(2, [10, 20, 40, 60, 65536]), (3, [65536, MASK]), (4, [65536, MASK])):
for value in values:
changed('state-field-%d-%d' % (col, value), 1, 1, col, value)
changed('root-has-parent', 1, 0, 1, 20)
changed('composite-missing-initial', 1, 0, 2, 0)
changed('leaf-has-initial', 1, 5, 2, 40)
chart = copy.deepcopy(base)
chart[1][1][1] = 30
chart[1][2][1] = 20
bad.append(('disconnected-parent-cycle', chart))
chart = copy.deepcopy(base)
chart[1] += [state(100 + i, 10) for i in range(59)]
bad.append(('sixty-five-states', chart))
for column, values in ((0, [0, 65536, 2]), (1, [0, 99, MASK]),
(2, [256, MASK]), (3, [MASK + 1, (1 << 64) - 1]),
(4, [MASK + 1]), (5, [-(1 << 63), -(1 << 31) - 1, 1 << 31, (1 << 63) - 1]),
(6, [2, MASK]), (7, [0, 99, MASK]), (8, [2, MASK]), (9, [65536, MASK])):
for value in values:
changed('transition-field-%d-%d' % (column, value), 2, 0, column, value)
for target, mode in ((20, 0), (0, 1), (0, 2), (60, 1)):
chart = copy.deepcopy(base)
chart[2][0][6:9] = [0, target, mode]
bad.append(('internal-irrelevant-fields-%d-%d' % (target, mode), chart))
changed('history-target-leaf', 2, 0, 8, 1)
chart = copy.deepcopy(base)
chart[2] += [transition(20 + i, 60, i) for i in range(9)]
bad.append(('nine-rules-in-inactive-source', chart))
chart = copy.deepcopy(base)
chart[2] = [transition(i + 1, 10, i % 256) for i in range(513)]
bad.append(('five-hundred-thirteen-transitions', chart))
for label, chart in bad:
obs.inspect(chart, 'invalid/' + label)
c('D 0 0', 'invalid-reset-keeps-old-machine/' + label, ['H09', 'H12', 'H26', 'H29'])
obs.inspect(base, 'recover-after-invalid-inputs')
# Noncanonical but legal limits, guards, priorities and stable numeric ties.
choice = [65535, [state(65535, 0, 2, 0, 0), state(2, 65535, 11, 65535, 0),
state(11, 2, 0, 0, 65535)],
[transition(9, 11, 0, required=1 << 31, priority=-(1 << 31), tag=0),
transition(2, 2, 0, priority=(1 << 31) - 1, tag=65535),
transition(100, 11, 1, priority=1), transition(20, 11, 1, priority=1),
transition(10, 11, 2, required=3, forbidden=2),
transition(11, 2, 2, forbidden=4), transition(1, 65535, 3, kind=1, target=11)]]
obs.inspect(choice, 'legal-wide-values-and-guard-overlap')
for code, flags in ((0, 0), (0, 1 << 31), (0, MASK), (1, 0), (2, 3), (2, 4), (3, 0), (255, 0)):
for op in ('Q', 'D'):
c('%s %d %d' % (op, code, flags), 'priority-guard-and-deepest-selection',
['H01', 'H06', 'H08', 'H15', 'H16', 'H17', 'H18', 'H19', 'H25', 'H31', 'H32'])
root_leaf = [65535, [state(65535, enter=0, leave=65535)],
[transition(65535, 65535, 255, kind=1, target=65535, tag=0)]]
obs.inspect(root_leaf, 'one-root-leaf-id-tag-boundaries')
c('D 255 0', 'root-leaf-external-self', ['H01', 'H19', 'H20', 'H23', 'H25', 'H32'])
obs.load([1, [state(1)], []], 'replace-input-without-reset')
c('D 255 0', 'machine-owns-prior-chart', ['H12', 'H29', 'H30'])
c('R', 'same-ids-new-chart-reset', ['H12', 'H29', 'H30'])
c('D 255 0', 'new-chart-has-no-old-handler', ['H17', 'H26', 'H29', 'H30'])
# Maximum chain and all transition slots; one root self event has 129 records.
nodes = [state(i, i - 1 if i > 1 else 0, i + 1 if i < 64 else 0,
0 if i % 2 else 65535, 65535 if i % 2 else 0) for i in range(1, 65)]
rules = [transition((source - 1) * 8 + k + 1, source, 20 + k, priority=k)
for source in range(1, 65) for k in range(8)]
rules[0] = transition(1, 1, 7, kind=1, target=1, tag=65535)
maximum = [1, list(reversed(nodes)), list(reversed(rules))]
obs.inspect(maximum, 'maximum-64-states-512-transitions')
c('Q 255 4294967295', 'maximum-full-no-enabled-scan', ['H05', 'H08', 'H15', 'H16', 'H35', 'H36'])
c('D 7 0', 'maximum-root-external-129-records', ['H19', 'H20', 'H21', 'H23', 'H25', 'H32', 'H35'])
obs.batch([[7, 0]] * 128, 'maximum-128-events-16512-records', ['H21', 'H22', 'H25', 'H27', 'H28', 'H35', 'H36'])
for last in (1, 63, 127):
events = [[7, 0]] * (last + 1)
events[-1] = [256, 0]
obs.batch(events, 'maximum-late-error-at-%d' % last)
c('P', 'maximum-late-error-keeps-all-history', ['H13', 'H21', 'H28', 'H29'])
c('K 3', 'maximum-saved-snapshot', ['H13', 'H29', 'H30'])
obs.inspect(small_chart(), 'reset-after-maximum')
c('O 3', 'maximum-old-snapshot-stays-independent', ['H13', 'H29', 'H30'])
rng = random.Random(1792236501)
for case in range(180):
count = rng.randrange(1, 22)
ids = rng.sample(range(1, 65536), count)
children = {ident: [] for ident in ids}
nodes = []
for position, ident in enumerate(ids):
parent = 0 if position == 0 else rng.choice(ids[:position])
if parent:
children[parent].append(ident)
nodes.append(state(ident, parent, enter=rng.choice([0, 65535, ident]), leave=rng.randrange(65536)))
for node in nodes:
node[2] = rng.choice(children[node[0]]) if children[node[0]] else 0
rules = []
composites = [node[0] for node in nodes if node[2]]
tid = rng.sample(range(1, 65536), count * 8)
for ident in ids:
for _ in range(rng.randrange(9)):
kind = rng.randrange(2)
mode = rng.randrange(2) if kind and composites else 0
target = rng.choice(composites if mode else ids) if kind else 0
rules.append(transition(tid[len(rules)], ident, rng.randrange(8), rng.randrange(16),
rng.randrange(16), rng.choice([-(1 << 31), -1, 0, 0, 1, (1 << 31) - 1]),
kind, target, mode, rng.choice([0, 65535, rng.randrange(65536)])))
rng.shuffle(nodes)
rng.shuffle(rules)
chart = [ids[0], nodes, rules]
assert valid_chart(chart)
obs.inspect(chart, 'varied-chart')
for operation in range(8):
code, flags = rng.randrange(10), rng.choice([rng.randrange(32), MASK, 1 << 31])
c('Q %d %d' % (code, flags), 'varied-selection', ['H08', 'H15', 'H16', 'H17', 'H29'])
c('D %d %d' % (code, flags), 'varied-external-internal-history',
['H18', 'H19', 'H20', 'H21', 'H22', 'H23', 'H24', 'H25', 'H26', 'H29'])
events = [[rng.randrange(10), rng.randrange(32)] for _ in range(rng.randrange(9))]
obs.batch(events, 'varied-batch-equivalent-sequence')
if case % 5 == 0:
obs.batch(events + [[256, 0]], 'varied-late-invalid-rollback')
c('Y 1', 'varied-clone-instance', ['H11', 'H29', 'H30'])
c('U 1', 'varied-clone-selected', ['H11', 'H29', 'H30'])
c('D 7 0', 'varied-clone-mutation', ['H11', 'H26', 'H29', 'H30'])
c('U 0', 'varied-source-retained', ['H11', 'H29', 'H30'])
if case % 7 == 0:
c('K 2', 'varied-save-snapshot', ['H13', 'H29', 'H30'])
c('R', 'varied-reset-clears-history', ['H12', 'H13', 'H34'])
c('O 2', 'varied-old-snapshot-independent', ['H13', 'H29', 'H30'])
return obs.commands, obs.expected, obs.labels
def main():
commands, expected, labels = plan()
scratch = Path(tempfile.mkdtemp(prefix='embedded-hard-fsm-', dir='/tmp'))
for name, content in CONTEXT.items():
(scratch / name).write_text(content)
for name in CANDIDATES:
(scratch / name).write_bytes((Path(sys.argv[1]) / name).read_bytes())
built = subprocess.run(['g++', '-std=c++17', '-O2', '-Wall', '-Wextra', '-pedantic',
'fsm_observe.cpp', *SOURCES, '-o', 'observe'], cwd=scratch,
text=True, encoding='utf-8', errors='replace', capture_output=True, timeout=30)
if built.returncode:
print('check=build clauses=H37,H38 build failed: ' + built.stderr[-1500:].replace('\n', ' '))
return 1
# shortcut: scratch is retained for container teardown; trusted-local exact cleanup is external.
# The parent never accesses the shared scratch again after the candidate child starts.
observed = subprocess.run([str(scratch / 'observe')], input='\n'.join(commands) + '\n', cwd=scratch,
text=True, encoding='utf-8', errors='replace', capture_output=True, timeout=15)
if observed.returncode:
print('check=execution clauses=H37,H38 exit=%d stderr=%s' % (observed.returncode, observed.stderr[-300:]))
return 1
actual = observed.stdout.splitlines()
failures = []
for index in range(max(len(actual), len(expected))):
raw = actual[index] if index < len(actual) else '<missing>'
try:
got = json.loads(raw)
except (ValueError, TypeError):
got = raw
want = expected[index] if index < len(expected) else '<end>'
if (index >= len(actual) or index >= len(expected) or
json.dumps(got, sort_keys=True) != json.dumps(want, sort_keys=True)):
label, clauses = labels[index] if index < len(labels) else ('extra-output', ('H38',))
failures.append((index, label, clauses, got, want))
if failures:
for index, label, clauses, got, want in failures[:20]:
print('check=%s clauses=%s observation=%d got=%r expected=%r' %
(label, ','.join(clauses), index, str(got)[:180], str(want)[:180]))
print('mismatches=%d observations=%d' % (len(failures), len(expected)))
return 1
print('PASS')
return 0
if __name__ == '__main__':
raise SystemExit(main())