init
This commit is contained in:
commit
0cba7f5ee0
385 changed files with 17912 additions and 0 deletions
284
tests/conformance.gd
Normal file
284
tests/conformance.gd
Normal file
|
|
@ -0,0 +1,284 @@
|
|||
extends SceneTree
|
||||
## Conformance runner (godot-plan.md §2). Replays traces written by the TS sim through the GDScript
|
||||
## engine, and stops each game at the first step that differs.
|
||||
##
|
||||
## godot --headless --script res://tests/conformance.gd -- [options]
|
||||
##
|
||||
## --traces DIR a trace set (a folder with an index.json) or a folder of them
|
||||
## (default res://tests/traces)
|
||||
## --limit N check at most N games per set
|
||||
## --check also check rule invariants after every step
|
||||
## --verbose print every game
|
||||
##
|
||||
## Make traces with tools/make_traces.sh, which runs the sim's src/trace.ts.
|
||||
##
|
||||
## A step's fingerprint is the action taken, an md5 of the legal action keys in order, of the state
|
||||
## (sorted-key JSON, without the card defs and log), of the log lines it added, and of the next
|
||||
## decider's view. A trace made with --full also holds every state, so a difference names the field;
|
||||
## one made with --labels also checks the move-list labels (Describe).
|
||||
|
||||
const DEFAULT_TRACES := "res://tests/traces"
|
||||
## Detailed reports printed per set before the rest are only counted.
|
||||
const MAX_REPORTS := 3
|
||||
|
||||
var _opts := {"traces": DEFAULT_TRACES, "limit": 0, "check": false, "verbose": false}
|
||||
var _pool: Dictionary
|
||||
var _cards_md5 := ""
|
||||
|
||||
|
||||
func _init() -> void:
|
||||
var args := OS.get_cmdline_user_args()
|
||||
var i := 0
|
||||
while i < args.size():
|
||||
match args[i]:
|
||||
"--traces":
|
||||
i += 1
|
||||
_opts.traces = args[i]
|
||||
"--limit":
|
||||
i += 1
|
||||
_opts.limit = int(args[i])
|
||||
"--check":
|
||||
_opts.check = true
|
||||
"--verbose":
|
||||
_opts.verbose = true
|
||||
_:
|
||||
printerr("conformance: unknown option %s" % args[i])
|
||||
quit(2)
|
||||
return
|
||||
i += 1
|
||||
quit(_run())
|
||||
|
||||
|
||||
func _run() -> int:
|
||||
var root: String = ProjectSettings.globalize_path(_opts.traces) if _opts.traces.begins_with("res://") else _opts.traces
|
||||
var sets := _find_sets(root)
|
||||
if sets.is_empty():
|
||||
print("conformance: no trace sets in %s (folders with an index.json)" % root)
|
||||
return 1
|
||||
_pool = Cards.load_cards()
|
||||
_cards_md5 = _md5(FileAccess.get_file_as_string(Cards.DEFAULT_CSV))
|
||||
var failed := 0
|
||||
for dir in sets:
|
||||
failed += _run_set(dir)
|
||||
print("conformance: %s" % ("all sets match" if failed == 0 else "%d game(s) differ" % failed))
|
||||
return 0 if failed == 0 else 1
|
||||
|
||||
|
||||
func _find_sets(root: String) -> Array:
|
||||
if FileAccess.file_exists(root.path_join("index.json")):
|
||||
return [root]
|
||||
var out := []
|
||||
var d := DirAccess.open(root)
|
||||
if d == null:
|
||||
return out
|
||||
var names := d.get_directories()
|
||||
names.sort()
|
||||
for n in names:
|
||||
if FileAccess.file_exists(root.path_join(n).path_join("index.json")):
|
||||
out.append(root.path_join(n))
|
||||
return out
|
||||
|
||||
|
||||
func _run_set(dir: String) -> int:
|
||||
var index: Dictionary = Util.ints(JSON.parse_string(FileAccess.get_file_as_string(dir.path_join("index.json"))))
|
||||
var set_name := dir.get_file()
|
||||
if index.get("cards", _cards_md5) != _cards_md5:
|
||||
print("%s: res://data/cards.csv differs from the CSV the traces were made from. Sync it, or remake the traces." % set_name)
|
||||
return 1
|
||||
if index.has("rngCheck"):
|
||||
var got := _rng_check(index.rngSeeds)
|
||||
if got != index.rngCheck:
|
||||
print("%s: Mulberry32 differs from TS (rng check %s, TS %s)" % [set_name, got, index.rngCheck])
|
||||
return 1
|
||||
var files := []
|
||||
for f in DirAccess.get_files_at(dir):
|
||||
if f.begins_with("game-") and f.ends_with(".json"):
|
||||
files.append(f)
|
||||
files.sort_custom(func(a, b): return _game_no(a) < _game_no(b))
|
||||
if _opts.limit > 0:
|
||||
files = files.slice(0, _opts.limit)
|
||||
var started := Time.get_ticks_msec()
|
||||
var failed := 0
|
||||
var steps := 0
|
||||
for f in files:
|
||||
var trace: Dictionary = JSON.parse_string(FileAccess.get_file_as_string(dir.path_join(f)))
|
||||
var result := _check_game(trace, index)
|
||||
steps += result.steps
|
||||
if result.error != "":
|
||||
failed += 1
|
||||
if failed <= MAX_REPORTS:
|
||||
print("%s/%s: %s" % [set_name, f, result.error])
|
||||
elif _opts.verbose:
|
||||
print("%s/%s: ok (%d steps)" % [set_name, f, result.steps])
|
||||
var secs := (Time.get_ticks_msec() - started) / 1000.0
|
||||
var summary := "%d/%d games match" % [files.size() - failed, files.size()]
|
||||
print("%s: %s (%d steps, %.1fs)" % [set_name, summary, steps, secs])
|
||||
return failed
|
||||
|
||||
|
||||
func _rng_check(seeds: Array) -> String:
|
||||
var lines := []
|
||||
for seed in seeds:
|
||||
var r := Rng.make(seed)
|
||||
var vals := PackedStringArray()
|
||||
vals.resize(10000)
|
||||
for i in 10000:
|
||||
vals[i] = str(roundi(Rng.next_float(r) * 4294967296.0))
|
||||
lines.append(",".join(vals))
|
||||
return _md5("\n".join(lines))
|
||||
|
||||
|
||||
## Replays one trace. Returns {steps, error}, with error "" when every step matches.
|
||||
func _check_game(t: Dictionary, index: Dictionary) -> Dictionary:
|
||||
var seed: int = int(t.seed)
|
||||
var rules := Rules.from_json(t.rules)
|
||||
var decks: Array = t.decks
|
||||
var hint := _full_hint(seed, index)
|
||||
var fail := func(step: int, msg: String) -> Dictionary:
|
||||
return {"steps": step, "error": "seed %d, %s%s" % [seed, msg, hint]}
|
||||
|
||||
# Dealing: the same decks from the same seed.
|
||||
var include := Callable()
|
||||
if t.pool is Array:
|
||||
var names := {}
|
||||
for n in t.pool:
|
||||
names[n] = true
|
||||
include = func(c): return names.has(c.name)
|
||||
Util.errors.clear()
|
||||
var dealt := Play.deal(_pool, seed, rules, include)
|
||||
if dealt != decks:
|
||||
return fail.call(0, "dealt different decks: %s vs TS %s" % [JSON.stringify(dealt), JSON.stringify(decks)])
|
||||
|
||||
var s = RulesEngine.create_game({"pool": _pool, "decks": decks, "seed": seed, "rules": rules, "log": true})
|
||||
if s == null or not Util.errors.is_empty():
|
||||
return fail.call(0, "create_game failed: %s" % "; ".join(Util.errors))
|
||||
var initial: Dictionary = t.initial
|
||||
var diff := _compare(s, t, 0, initial.state, initial.log, s.log, initial.get("view", ""))
|
||||
if diff != "":
|
||||
return fail.call(0, "after setup: %s" % diff)
|
||||
|
||||
var makers := Play.bots()
|
||||
var bots := []
|
||||
for i in 2:
|
||||
var b: String = t.bots[i]
|
||||
bots.append(makers[b].call(seed * 2 + 1 + i) if makers.has(b) else null)
|
||||
|
||||
var steps: Array = t.steps
|
||||
for i in steps.size():
|
||||
var step: Dictionary = steps[i]
|
||||
var at := "step %d (%s)" % [i + 1, step.a]
|
||||
if s.over:
|
||||
return fail.call(i, "%s: the game is already over" % at)
|
||||
var p: int = RulesEngine.decider(s)
|
||||
var legal := RulesEngine.legal_actions(s)
|
||||
var keys := PackedStringArray()
|
||||
for a in legal:
|
||||
keys.append(RulesEngine.action_key(a))
|
||||
if _md5("\n".join(keys)) != step.l:
|
||||
return fail.call(i, "%s: legal actions differ. GDScript has %d:\n %s" % [at, keys.size(), "\n ".join(keys)])
|
||||
var k := keys.find(step.a)
|
||||
if k < 0:
|
||||
return fail.call(i, "%s: TS's action isn't legal in GDScript" % at)
|
||||
if step.has("d"):
|
||||
var labels := PackedStringArray()
|
||||
for a in legal:
|
||||
labels.append(Describe.describe_action(s, a))
|
||||
if _md5("\n".join(labels)) != step.d:
|
||||
return fail.call(i, "%s: move labels differ. GDScript has:\n %s" % [at, "\n ".join(labels)])
|
||||
if bots[p] != null:
|
||||
var pick: Dictionary = bots[p].choose(RulesEngine.view_for(s, p), legal, p)
|
||||
if RulesEngine.action_key(pick) != step.a:
|
||||
return fail.call(i, "%s: the %s bot picked %s" % [at, t.bots[p], RulesEngine.action_key(pick)])
|
||||
var logged: int = s.log.size()
|
||||
RulesEngine.apply_action(s, legal[k], legal)
|
||||
if not Util.errors.is_empty():
|
||||
return fail.call(i, "%s: engine error: %s" % [at, "; ".join(Util.errors)])
|
||||
diff = _compare(s, t, i + 1, step.s, step.g, s.log.slice(logged), step.get("v", ""))
|
||||
if diff != "":
|
||||
return fail.call(i, "after %s: %s" % [at, diff])
|
||||
if _opts.check:
|
||||
var errors := Invariants.check(s)
|
||||
if not errors.is_empty():
|
||||
return fail.call(i, "after %s: invariants: %s" % [at, "; ".join(errors)])
|
||||
var end: Dictionary = Util.ints(t.end)
|
||||
var got := {"winner": s.winner, "turn": s.turn, "endReason": s.endReason}
|
||||
if not s.over or got != end:
|
||||
return fail.call(steps.size(), "the game ends %s, TS %s" % [JSON.stringify(got), JSON.stringify(end)])
|
||||
return {"steps": steps.size(), "error": ""}
|
||||
|
||||
|
||||
## Compares the state after step `n` with the trace's fingerprints. Returns "" when they match.
|
||||
func _compare(s: Dictionary, t: Dictionary, n: int, state_md5: String, log_md5: String, new_lines: Array, view_md5: String) -> String:
|
||||
var body := _body(s)
|
||||
if _md5(JSON.stringify(body)) != state_md5:
|
||||
if t.has("states"):
|
||||
var want = Util.ints(t.states[n])
|
||||
var have = Util.ints(JSON.parse_string(JSON.stringify(body)))
|
||||
var where := _diff(want, have, "")
|
||||
return "state differs: %s" % (where if where != "" else "(no field differs; JSON formatting?)")
|
||||
return "state differs"
|
||||
if _md5(JSON.stringify(new_lines)) != log_md5:
|
||||
return "log differs. GDScript wrote:\n %s" % "\n ".join(new_lines.map(func(l): return JSON.stringify(l)))
|
||||
if view_md5 != "" and not s.over:
|
||||
var view := _body(RulesEngine.view_for(s, RulesEngine.decider(s)))
|
||||
if _md5(JSON.stringify(view)) != view_md5:
|
||||
return "the decider's view differs"
|
||||
return ""
|
||||
|
||||
|
||||
## The state as fingerprinted: without its card defs (fixed for the game) and log (checked by line).
|
||||
func _body(s: Dictionary) -> Dictionary:
|
||||
var b := s.duplicate()
|
||||
b.erase("defs")
|
||||
b.erase("log")
|
||||
return b
|
||||
|
||||
|
||||
## The first path where two JSON values differ, like "players[1].anomalies[0].damage ts=4 gd=3".
|
||||
func _diff(want: Variant, have: Variant, path: String) -> String:
|
||||
if typeof(want) != typeof(have):
|
||||
return "%s ts=%s gd=%s" % [path, JSON.stringify(want), JSON.stringify(have)]
|
||||
if want is Dictionary:
|
||||
var keys: Array = want.keys()
|
||||
for k in have.keys():
|
||||
if not keys.has(k):
|
||||
keys.append(k)
|
||||
keys.sort()
|
||||
for k in keys:
|
||||
var sub := "%s.%s" % [path, k] if path != "" else str(k)
|
||||
if not want.has(k):
|
||||
return "%s ts=(missing) gd=%s" % [sub, JSON.stringify(have[k])]
|
||||
if not have.has(k):
|
||||
return "%s ts=%s gd=(missing)" % [sub, JSON.stringify(want[k])]
|
||||
var d := _diff(want[k], have[k], sub)
|
||||
if d != "":
|
||||
return d
|
||||
return ""
|
||||
if want is Array:
|
||||
for i in mini(want.size(), have.size()):
|
||||
var d := _diff(want[i], have[i], "%s[%d]" % [path, i])
|
||||
if d != "":
|
||||
return d
|
||||
if want.size() != have.size():
|
||||
return "%s length ts=%d gd=%d" % [path, want.size(), have.size()]
|
||||
return ""
|
||||
return "" if want == have else "%s ts=%s gd=%s" % [path, JSON.stringify(want), JSON.stringify(have)]
|
||||
|
||||
|
||||
func _full_hint(seed: int, index: Dictionary) -> String:
|
||||
if index.get("full", false):
|
||||
return ""
|
||||
var cmd := "node src/trace.ts --out /tmp/trace-full --seed %d -n 1 --full --south %s --north %s" % [seed, index.bots[0], index.bots[1]]
|
||||
if index.get("pool", "all") != "all":
|
||||
cmd += " --pool %s" % index.pool
|
||||
for r in index.get("rules", []):
|
||||
cmd += " --rule %s" % r
|
||||
return "\n For the differing field, in files-tcg/sim: %s\n then: --traces /tmp/trace-full" % cmd
|
||||
|
||||
|
||||
static func _md5(text: String) -> String:
|
||||
return text.md5_text().substr(0, 12)
|
||||
|
||||
|
||||
static func _game_no(file: String) -> int:
|
||||
return file.trim_prefix("game-").trim_suffix(".json").to_int()
|
||||
Loading…
Add table
Add a link
Reference in a new issue