A Civilization-style strategy game about governing Israel from 15 May 1948. Real ministers, real map, every fact sourced. Unity + deterministic C# sim.
sim: invariant checks with tolerance bands on the golden runs (fixes #294) (#309)
agamrafaeli-instinct471c30032465
diff --git a/docs/determinism.md b/docs/determinism.mdindex 2ee6f084a..8266ebcf3 100644--- a/docs/determinism.md+++ b/docs/determinism.md@@ -48,6 +48,15 @@ never take a hash from the run without the variable, so a second plain run is thhash), add a row to the rebaseline history, and say why in the commit message. The snapshot test also fails if a snapshot isstale while the hash is unchanged.+**Invariants.** A hash says something changed; `sim/Statecraft.Sim.Tests/golden/invariants.yaml` says whether it is+still plausible. Each entry names a golden run (`1950` or `1952`), a value (an indicator id, or `treasury`, `debt`,+`fx`, `population`, `stability`), when it is read (`end`, `always`, or a date: the first state on or after it), a `min`+and/or `max`, and a `reason` (a source, or the test or note the band comes from). `InvariantTests` plays the golden runs+and fails with the check, the value, the date and the band, for example `invariant 'foreign-currency-runs-out' (...): fx+= 12.5 on 1952-02-27 is outside [-inf, 0]`. The invariants only add checks: a tuned rate that stays in its band still+moves the hash goldens (rebaseline as above), but not an invariant. The shipped bands are loose guards set around the+current runs; the design document and the maintainers decide which ranges matter.+**Rules per era.** A system reads `Content.RulesAt(date)`, where `date` is the date of the state the turn starts from (`s.Date`before the step); `AttentionSystem.Refill` runs after the date moves, so it fills the next turn from that turn's era. Ruleschange only at era boundaries (chapters spec section 3.3). Spec section 4.1 will end the turn that reaches a boundary exactlydiff --git a/sim/Statecraft.Sim.Tests/InvariantTests.cs b/sim/Statecraft.Sim.Tests/InvariantTests.csnew file mode 100644index 000000000..e2be70d34--- /dev/null+++ b/sim/Statecraft.Sim.Tests/InvariantTests.cs@@ -0,0 +1,108 @@+using System;+using System.Collections.Generic;+using System.Linq;+using Statecraft.Sim;++/// <summary>Invariant checks (#294): the committed file passes on the real golden runs, and the runner and the format checks+/// fail the way they should, with the check, the value and the band in the message.</summary>+public class InvariantTests+{+ static readonly Content C = ContentLoader.Load(RealContentTests.ContentRoot());++ [Fact]+ public void TheCommittedInvariantsHoldOnTheGoldenRuns()+ {+ var all = Invariants.Parse(System.IO.File.ReadAllText(Invariants.FilePath()));+ Assert.NotEmpty(all);+ var failures = new List<string>();+ foreach (var run in Invariants.Runs)+ {+ var mine = all.Where(i => i.Run == run).ToList();+ if (mine.Count == 0) continue;+ var states = Invariants.History(C, Invariants.Until(run));+ Assert.Equal(GoldenRun.Play(C, Invariants.Until(run)).Hash(), states[states.Count - 1].Hash()); // the same run the goldens pin+ failures.AddRange(Invariants.Evaluate(mine, states));+ }+ Assert.True(failures.Count == 0, string.Join("\n", failures));+ }++ static List<GameState> Fixture3()+ {+ var a = Simulation.NewGame(C, GoldenRun.Seed, Mode.Historical);+ var b = a.Clone(); b.Date = new DateTime(1949, 1, 1); b.Treasury = 10; b.FxReserves = 5;+ var c = b.Clone(); c.Date = new DateTime(1950, 1, 1); c.Treasury = 30; c.FxReserves = -2;+ return new List<GameState> { a, b, c };+ }++ static Invariant Inv(string value, string when, double? min, double? max) =>+ new Invariant { Name = "t", Run = "1950", Value = value, When = when, Min = min, Max = max, Reason = "test" };++ [Fact]+ public void AValueInsideItsBandPasses()+ {+ Assert.Empty(Invariants.Evaluate(new[] { Inv("treasury", "end", 20, 40), Inv("treasury", "1949-01-01", 5, 15), Inv("fx", "always", -5, 100) }, Fixture3()));+ }++ [Fact]+ public void AFailureNamesTheCheckTheValueAndTheBand()+ {+ var f = Invariants.Evaluate(new[] { new Invariant { Name = "treasury-high", Run = "1950", Value = "treasury", When = "end", Max = 25, Reason = "why" } }, Fixture3()).Single();+ Assert.Contains("treasury-high", f);+ Assert.Contains("treasury = 30", f);+ Assert.Contains("1950-01-01", f);+ Assert.Contains("[-inf, 25]", f);+ Assert.Contains("why", f);+ }++ [Fact]+ public void AlwaysFailsOnTheFirstStateThatLeavesTheBandAndReportsItOnce()+ {+ var f = Invariants.Evaluate(new[] { Inv("fx", "always", 0, null) }, Fixture3());+ Assert.Single(f);+ Assert.Contains("fx = -2", f[0]);+ }++ [Fact]+ public void ADateUsesTheFirstStateOnOrAfterIt()+ {+ Assert.Single(Invariants.Evaluate(new[] { Inv("treasury", "1949-06-01", 0, 20) }, Fixture3())); // 1950-01-01 is the first on or after it: 30+ Assert.Single(Invariants.Evaluate(new[] { Inv("treasury", "2000-01-01", 0, 20) }, Fixture3())); // the run ends first+ }++ [Fact]+ public void ANonFiniteValueFailsWhateverTheBand()+ {+ var states = Fixture3();+ states[2].FxReserves = double.NaN;+ Assert.Contains("fx = NaN", Invariants.Evaluate(new[] { Inv("fx", "end", -5, 100) }, states).Single());+ states[2].FxReserves = double.PositiveInfinity;+ Assert.Single(Invariants.Evaluate(new[] { Inv("fx", "end", -5, null) }, states));+ }++ [Fact]+ public void AnUnknownValueFails()+ {+ Assert.Contains("neither a state value nor an indicator", Invariants.Evaluate(new[] { Inv("no_such", "end", 0, 1) }, Fixture3()).Single());+ }++ [Fact]+ public void AnIndicatorIsReadById()+ {+ var states = Fixture3();+ var id = states[0].Indicators.Keys.OrderBy(k => k, StringComparer.Ordinal).First();+ Assert.Empty(Invariants.Evaluate(new[] { Inv(id, "end", states[2].Indicators[id] - 0.001, states[2].Indicators[id] + 0.001) }, states));+ }++ [Theory]+ [InlineData("invariants:\n - {name: a, run: '1950', value: fx, when: end, min: 0}\n", "no reason or source")]+ [InlineData("invariants:\n - {name: a, run: '1950', value: fx, when: end, reason: r}\n", "neither min nor max")]+ [InlineData("invariants:\n - {name: a, run: '1950', value: fx, when: end, min: 5, max: 1, reason: r}\n", "min above max")]+ [InlineData("invariants:\n - {name: a, run: '1960', value: fx, when: end, min: 0, reason: r}\n", "names run '1960'")]+ [InlineData("invariants:\n - {name: a, run: '1950', value: fx, when: sometime, min: 0, reason: r}\n", "when 'sometime'")]+ [InlineData("invariants:\n - {name: a, run: '1950', value: fx, when: end, min: 0, reason: r}\n - {name: a, run: '1950', value: fx, when: end, min: 0, reason: r}\n", "listed twice")]+ public void AMalformedInvariantIsRefusedWithTheProblemNamed(string yaml, string expected)+ {+ var e = Assert.Throws<System.IO.InvalidDataException>(() => Invariants.Parse(yaml));+ Assert.Contains(expected, e.Message);+ }+}diff --git a/sim/Statecraft.Sim.Tests/Invariants.cs b/sim/Statecraft.Sim.Tests/Invariants.csnew file mode 100644index 000000000..32b33853b--- /dev/null+++ b/sim/Statecraft.Sim.Tests/Invariants.cs@@ -0,0 +1,128 @@+using System;+using System.Collections.Generic;+using System.Globalization;+using System.IO;+using System.Linq;+using Statecraft.Sim;+using YamlDotNet.Serialization;+using YamlDotNet.Serialization.NamingConventions;++/// <summary>Invariant checks with tolerance bands (#294), read from sim/Statecraft.Sim.Tests/golden/invariants.yaml and+/// evaluated on the golden runs. A hash golden says "something changed"; an invariant says "it is still plausible". The+/// invariants only add checks: a tuned number still moves the hash goldens, which are rebaselined as before+/// (docs/determinism.md). Each one carries a reason or source, like content does.</summary>+public sealed class Invariant+{+ public string Name { get; set; } = "";+ /// <summary>The golden run: "1950" or "1952" (GoldenRun.Until1950 / Until1952).</summary>+ public string Run { get; set; } = "";+ /// <summary>An indicator id, or treasury, debt, fx, population, stability.</summary>+ public string Value { get; set; } = "";+ /// <summary>"end" (the run's final state), a date yyyy-MM-dd (the first state on or after it), or "always" (every state).</summary>+ public string When { get; set; } = "";+ public double? Min { get; set; }+ public double? Max { get; set; }+ /// <summary>Why this band: a source, or the test or design note it comes from.</summary>+ public string Reason { get; set; } = "";+}++public static class Invariants+{+ public static readonly string[] Runs = { "1950", "1952" };+ static readonly string[] Named = { "treasury", "debt", "fx", "population", "stability" };++ public static string FilePath() =>+ Path.Combine(Directory.GetParent(RealContentTests.ContentRoot())!.FullName, "sim", "Statecraft.Sim.Tests", "golden", "invariants.yaml");++ sealed class FileModel { public List<Invariant> Invariants { get; set; } = new List<Invariant>(); }++ public static List<Invariant> Parse(string yaml)+ {+ var d = new DeserializerBuilder().WithNamingConvention(UnderscoredNamingConvention.Instance).Build();+ var list = d.Deserialize<FileModel>(yaml)?.Invariants ?? new List<Invariant>();+ foreach (var e in Problems(list)) throw new InvalidDataException(e);+ return list;+ }++ /// <summary>Format errors, one per line: a missing name, reason or band, an unknown run or when, a duplicate name.</summary>+ public static IEnumerable<string> Problems(IReadOnlyList<Invariant> all)+ {+ foreach (var i in all)+ {+ var who = $"invariant '{i.Name}'";+ if (string.IsNullOrWhiteSpace(i.Name)) yield return "an invariant has no name";+ if (string.IsNullOrWhiteSpace(i.Reason)) yield return $"{who} has no reason or source";+ if (i.Min == null && i.Max == null) yield return $"{who} has neither min nor max";+ if (i.Min != null && i.Max != null && i.Min > i.Max) yield return $"{who} has min above max";+ if (!Runs.Contains(i.Run)) yield return $"{who} names run '{i.Run}' (known: {string.Join(", ", Runs)})";+ if (string.IsNullOrWhiteSpace(i.Value)) yield return $"{who} has no value";+ if (i.When != "end" && i.When != "always" && !DateTime.TryParseExact(i.When, "yyyy-MM-dd", CultureInfo.InvariantCulture, DateTimeStyles.None, out _))+ yield return $"{who} has when '{i.When}' (use end, always or yyyy-MM-dd)";+ }+ foreach (var g in all.GroupBy(i => i.Name).Where(g => g.Key != "" && g.Count() > 1)) yield return $"invariant '{g.Key}' is listed twice";+ }++ /// <summary>The value on a state; null when the id is not a state value or an indicator of this state.</summary>+ public static double? Read(GameState s, string what)+ {+ switch (what)+ {+ case "treasury": return s.Treasury;+ case "debt": return s.Debt;+ case "fx": return s.FxReserves;+ case "population": return s.TotalPopulation;+ case "stability": return s.CoalitionStability;+ }+ return s.Indicators.TryGetValue(what, out var v) ? v : (double?)null;+ }++ /// <summary>Failures of the invariants for one run, given its states in order. Each names the check, the value and the band.</summary>+ public static List<string> Evaluate(IReadOnlyList<Invariant> invariants, IReadOnlyList<GameState> states)+ {+ var failures = new List<string>();+ foreach (var i in invariants)+ {+ IEnumerable<GameState> at;+ if (i.When == "end") at = new[] { states[states.Count - 1] };+ else if (i.When == "always") at = states;+ else+ {+ var date = DateTime.ParseExact(i.When, "yyyy-MM-dd", CultureInfo.InvariantCulture);+ var s = states.FirstOrDefault(x => x.Date >= date);+ if (s == null) { failures.Add($"{Describe(i)}: the run ends before {i.When}"); continue; }+ at = new[] { s };+ }+ foreach (var s in at)+ {+ var v = Read(s, i.Value);+ if (v == null) { failures.Add($"{Describe(i)}: '{i.Value}' is neither a state value nor an indicator"); break; }+ // NaN compares false with every bound, so it would sit inside any band; a non-finite value always fails.+ if (double.IsNaN(v.Value) || double.IsInfinity(v.Value) || (i.Min != null && v < i.Min) || (i.Max != null && v > i.Max))+ {+ failures.Add($"{Describe(i)}: {i.Value} = {v.Value.ToString("0.###", CultureInfo.InvariantCulture)} on {s.Date:yyyy-MM-dd} is outside {Band(i)}");+ if (i.When == "always") break; // the first state that leaves the band is enough+ }+ }+ }+ return failures;+ }++ static string Describe(Invariant i) => $"invariant '{i.Name}' (run {i.Run}, {i.When}; {i.Reason})";+ static string Band(Invariant i) =>+ $"[{(i.Min == null ? "-inf" : i.Min.Value.ToString("0.###", CultureInfo.InvariantCulture))}, {(i.Max == null ? "+inf" : i.Max.Value.ToString("0.###", CultureInfo.InvariantCulture))}]";++ /// <summary>The golden run's states, stepped exactly as <see cref="GoldenRun.Play"/> does.</summary>+ public static List<GameState> History(Content c, DateTime until)+ {+ var s = Simulation.NewGame(c, GoldenRun.Seed, Mode.Historical);+ var h = new List<GameState> { s };+ for (int turn = 0; turn < 1000 && s.Date < until && s.GameOver == null; turn++)+ {+ s = Simulation.Step(c, s, HistoricalAI.Commands(c, s)).State;+ h.Add(s);+ }+ return h;+ }++ public static DateTime Until(string run) => run == "1950" ? GoldenRun.Until1950 : GoldenRun.Until1952;+}diff --git a/sim/Statecraft.Sim.Tests/golden/invariants.yaml b/sim/Statecraft.Sim.Tests/golden/invariants.yamlnew file mode 100644index 000000000..cc51abfd5--- /dev/null+++ b/sim/Statecraft.Sim.Tests/golden/invariants.yaml@@ -0,0 +1,40 @@+# Invariant checks with tolerance bands (#294), evaluated on the golden runs by InvariantTests. A hash golden says+# "something changed"; these say "it is still plausible". They only add checks: a tuned number still moves the hash+# goldens, which are rebaselined as before (docs/determinism.md).+#+# Fields: name, run (1950 or 1952), value (an indicator id, or treasury, debt, fx, population, stability),+# when (end | always | yyyy-MM-dd = the first state on or after that date), min and/or max, reason (a source, or the+# test or note the band comes from). A failure names the check, the value and the band.+#+# These first bands are loose guards set around the current runs. Which ranges matter comes from the design document+# and the maintainers: replace or tighten them there.+invariants:+ - name: foreign-currency-runs-out+ run: 1952+ value: fx+ when: end+ max: 0+ reason: "Foreign currency ran out in autumn 1951 (FRUS 1951 v.V doc 513); capital_inflow_per_year is tuned to it (EconomyCalibrationTests)."++ - name: debt-grows-through-the-run+ run: 1952+ value: debt+ when: end+ min: 100+ max: 300+ reason: "Internal debt rose IL 98.4m over 1950-51 (Michaely 1975, Table 5-2), and the budget is financed by borrowing (EconomyCalibrationTests). Wide band around the current run."++ - name: population-stays-in-range+ run: 1952+ value: population+ when: always+ min: 600000+ max: 1800000+ reason: "Plausibility guard, not a sourced range: the run starts at 649,400 (rules.yaml initial_population) and ends near 1.4 million after the immigration of 1948-51. The band catches a run that loses people or runs away."++ - name: coalition-stays-clear-of-collapse+ run: 1952+ value: stability+ when: always+ min: 0.35+ reason: "The run must not approach PoliticsSystem.CollapseBelow (0.2); ThePlaythroughSurvivesTo1952 checks the game does not end."