Skip to content

A Civilization-style strategy game about governing Israel from 15 May 1948. Real ministers, real map, every fact sourced. Unity + deterministic C# sim.

sim: era golden helper (refs #292) (#312)

agamrafaeli-instinct6d439a7c0e5b
diff --git a/docs/determinism.md b/docs/determinism.md
index fe41c9ad0..eeb49656a 100644
--- a/docs/determinism.md
+++ b/docs/determinism.md
@@ -48,6 +48,16 @@ never take a hash from the run without the variable, so a second plain run is th
hash), add a row to the rebaseline history, and say why in the commit message. The snapshot test also fails if a snapshot is
stale while the hash is unchanged.
+**Adding an era golden.** In a test, call `EraGolden.Check("hash_<era>_<year>", content, "<era id>", new DateTime(<year>, 1, 1))`. It plays a fresh
+start of that era (golden seed unless one is passed, Historical mode, `HistoricalAI`, the same loop as `GoldenRun.Play`) and checks the hash
+against the manifest line of that name and the snapshot `golden/<name>.txt`. The run stays inside the era: it stops before the turn that would
+reach the era's `to`, because that turn ends on the boundary and its state already holds the next era's attention and events, so the
+next era's rules would move this era's golden (`EraGoldenTests.TheRunStaysInsideTheEraSoTheNextErasRulesDoNotMoveIt`). Bless it with `STATECRAFT_UPDATE_GOLDEN=1 dotnet test sim/Statecraft.sln`, which adds the
+manifest line and the snapshot; list the name in `GoldenManifestTests.TheManifestHoldsExactlyTheKnownGoldens`. Today only the first era can
+be started fresh, because `NewGame` reads the base rules' start; a later era fails with a message saying its start values are not read yet.
+The carry-over check (play era N into N+1 and compare with a fresh N+1 on each carried quantity, chapters design section 6) waits on that
+and on `EraSystem.Cross`.
+
**Scenario goldens.** The two hash goldens follow `HistoricalAI`, the path history took. A scenario is a path a player might take
instead: `sim/Statecraft.Sim.Tests/scenarios/<name>.yaml` lists commands by date (`on:`), the runner (`Scenario`, in the tests) plays
them from a seed (default 1948) in Historical mode until `until:`, and `ScenarioTests` checks the final hash against the manifest line
diff --git a/sim/Statecraft.Sim.Tests/EraGolden.cs b/sim/Statecraft.Sim.Tests/EraGolden.cs
new file mode 100644
index 000000000..9e2e36ff1
--- /dev/null
+++ b/sim/Statecraft.Sim.Tests/EraGolden.cs
@@ -0,0 +1,39 @@
+using System;
+using System.Linq;
+using Statecraft.Sim;
+
+/// <summary>Adds a golden for one era in a few lines (#292): <c>EraGolden.Check("hash_founding_1950", c, "founding", new DateTime(1950, 1, 1))</c>
+/// plays a fresh start of that era (golden seed, Historical mode, HistoricalAI, as <see cref="GoldenRun.Play"/> does) and
+/// checks its hash against the manifest line and its snapshot in golden/&lt;name&gt;.txt, with the readable diff on a mismatch.
+/// Bless a new one with STATECRAFT_UPDATE_GOLDEN=1 (docs/determinism.md).
+/// The run stays inside the era: it stops before the turn that would reach the era's <c>to</c>. That turn ends on the boundary
+/// (spec 4.1), and its final state already holds the next era's attention and events, so the next era's rules would move
+/// this era's golden.
+/// A fresh start of an era later than the first needs that era's sourced start values, which NewGame does not read yet
+/// (it reads the base rules' start), so such an era fails here with a message saying so, not with a quiet wrong run.</summary>
+public static class EraGolden
+{
+ public static GameState Play(Content c, string eraId, DateTime until, ulong seed = GoldenRun.Seed)
+ {
+ var era = c.Eras.FirstOrDefault(e => e.Id == eraId) ?? throw new ArgumentException($"no era '{eraId}' (known: {string.Join(", ", c.Eras.Select(e => e.Id))})");
+ if (era.From != c.Rules.Start)
+ throw new NotSupportedException($"era '{eraId}' starts {era.From:yyyy-MM-dd}, but a new game starts {c.Rules.Start:yyyy-MM-dd}: a fresh start of a later era needs that era's start values, which are not read yet (chapters design section 6).");
+ if (until <= era.From || until > era.To) throw new ArgumentException($"until {until:yyyy-MM-dd} is outside era '{eraId}' ({era.From:yyyy-MM-dd} to {era.To:yyyy-MM-dd})");
+ // GoldenRun.Play's loop, except that a turn ending on or after the era's end is not taken.
+ var s = Simulation.NewGame(c, seed, Mode.Historical);
+ for (int turn = 0; turn < 1000 && s.Date < until && s.GameOver == null; turn++)
+ {
+ var next = Simulation.Step(c, s, HistoricalAI.Commands(c, s)).State;
+ if (next.Date >= era.To) break;
+ s = next;
+ }
+ return s;
+ }
+
+ public static void Check(string name, Content c, string eraId, DateTime until, ulong seed = GoldenRun.Seed)
+ {
+ var s = Play(c, eraId, until, seed);
+ var expected = GoldenManifest.UpdateRequested ? GoldenManifest.Read().GetValueOrDefault(name, "") : GoldenManifest.Expected(name);
+ GoldenSnapshot.Check(name, s, expected);
+ }
+}
diff --git a/sim/Statecraft.Sim.Tests/EraGoldenTests.cs b/sim/Statecraft.Sim.Tests/EraGoldenTests.cs
new file mode 100644
index 000000000..db43911f7
--- /dev/null
+++ b/sim/Statecraft.Sim.Tests/EraGoldenTests.cs
@@ -0,0 +1,69 @@
+using System;
+using System.Collections.Generic;
+using System.IO;
+using Statecraft.Sim;
+
+/// <summary>The era golden helper (#292).</summary>
+public class EraGoldenTests
+{
+ static readonly Content Real = ContentLoader.Load(RealContentTests.ContentRoot());
+
+ [Fact]
+ public void TheFoundingEraPlaysTheSameRunAsTheExistingGolden() =>
+ Assert.Equal(GoldenRun.Hash1950, EraGolden.Play(Real, "founding", GoldenRun.Until1950).Hash());
+
+ [Fact]
+ public void CheckOnTheFoundingEraMatchesThePinnedHash1950AndItsSnapshot() =>
+ EraGolden.Check("hash1950", Real, "founding", GoldenRun.Until1950); // the manifest line and golden/hash1950.txt
+
+ static Content TwoEras(string? secondRules = null)
+ {
+ var dir = Fixture.Write(new Dictionary<string, string>
+ {
+ ["eras.yaml"] = "eras:\n - {id: first, name: One, from: 1948-05-15, to: 1948-12-01}\n - {id: second, name: Two, from: 1948-12-01, to: 1949-06-01}\n",
+ });
+ if (secondRules != null)
+ {
+ Directory.CreateDirectory(Path.Combine(dir, "rules"));
+ File.WriteAllText(Path.Combine(dir, "rules", "second.yaml"), secondRules);
+ }
+ return ContentLoader.Load(dir);
+ }
+
+ [Theory]
+ [InlineData(1948, 11, 1)] // the fixture's quarterly turn from 12 September would end on the boundary, 1 December
+ [InlineData(1948, 12, 1)] // the era's end
+ public void TheRunStaysInsideTheEraSoTheNextErasRulesDoNotMoveIt(int y, int m, int d)
+ {
+ var plain = EraGolden.Play(TwoEras(), "first", new DateTime(y, m, d));
+ var overridden = EraGolden.Play(TwoEras("attention_per_turn: 7\n"), "first", new DateTime(y, m, d));
+ Assert.True(plain.Date < new DateTime(1948, 12, 1), $"the run ended on {plain.Date:yyyy-MM-dd}, in the next era");
+ Assert.Equal(plain.Hash(), overridden.Hash());
+ }
+
+ [Fact]
+ public void TheSeedIsUsed() =>
+ Assert.NotEqual(EraGolden.Play(TwoEras(), "first", new DateTime(1948, 11, 1)).RngState, EraGolden.Play(TwoEras(), "first", new DateTime(1948, 11, 1), seed: 7).RngState);
+
+ [Fact]
+ public void TheFirstEraOfAFixturePlays()
+ {
+ var s = EraGolden.Play(TwoEras(), "first", new DateTime(1948, 8, 1));
+ Assert.True(s.Date >= new DateTime(1948, 8, 1));
+ }
+
+ [Fact]
+ public void ALaterEraSaysItsStartValuesAreNotReadYet()
+ {
+ var e = Assert.Throws<NotSupportedException>(() => EraGolden.Play(TwoEras(), "second", new DateTime(1949, 3, 1)));
+ Assert.Contains("start values", e.Message);
+ Assert.Contains("1948-12-01", e.Message);
+ }
+
+ [Fact]
+ public void AnUnknownEraAndADateOutsideTheEraAreRefused()
+ {
+ Assert.Contains("known: first, second", Assert.Throws<ArgumentException>(() => EraGolden.Play(TwoEras(), "third", new DateTime(1948, 8, 1))).Message);
+ Assert.Contains("outside era", Assert.Throws<ArgumentException>(() => EraGolden.Play(TwoEras(), "first", new DateTime(1949, 1, 1))).Message);
+ }
+}