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.

feat(sim): GoldenRun; reject overlapping legislatures and governments, terms past abolition or death

eyalgolan980a16e4a76d
diff --git a/docs/determinism.md b/docs/determinism.md
index d20be0396..fbee3835b 100644
--- a/docs/determinism.md
+++ b/docs/determinism.md
@@ -12,24 +12,32 @@ The simulation must produce the same state, bit for bit, on .NET, Unity Mono and
- **Canonical hash:** `GameState.Hash()` is SHA-256 over a canonical text. Keys are sorted ordinally. Doubles are
written as IEEE bit patterns, with -0.0 written as 0.0. Culture is invariant.
-## Golden playthrough
+## Golden playthroughs
-The playthrough loads the real `content/` and calls `Simulation.NewGame(content, 1948, Mode.Historical)`. It then
-steps with `HistoricalAI.Commands` until `Date >= 1950-01-01`; with the current rules this ends on 1950-02-26 at
-turn 45. The final `GameState.Hash()` must equal:
+`Statecraft.Sim.GoldenRun.Play(content, until)` starts `Simulation.NewGame(content, GoldenRun.Seed, Mode.Historical)`
+with `GoldenRun.Seed = 1948` on the real `content/`, then steps with `HistoricalAI.Commands` until `Date >= until`
+(or the game ends, or 1000 turns pass). Each run's final `GameState.Hash()` is pinned:
-```
-eb9756528eeebdc7b078ab90f7fe7a349edcfc94be9543e5f20f258da4e500e9
-```
+| Run | Ends | Hash |
+|---|---|---|
+| to 1950-01-01 (`Hash1950`) | 1950-02-26, turn 45 | `eb9756528eeebdc7b078ab90f7fe7a349edcfc94be9543e5f20f258da4e500e9` |
-The constant is asserted in two places:
-- `sim/Statecraft.Sim.Tests/DeterminismTests.cs` (`GoldenHash`), on .NET.
-- `unity/Assets/Tests/EditMode/SimSmokeTests.cs` (`GoldenHash`), inside Unity (plan Task 23).
+Each constant is written in three places that must agree:
+- `sim/Statecraft.Sim/GoldenRun.cs`, which Unity code and players compare against;
+- `sim/Statecraft.Sim.Tests/DeterminismTests.cs`, which pins the value on .NET and asserts the library constant equals it;
+- this file.
-So far the hash is verified on .NET and Unity editor Mono; IL2CPP/WebGL pending M3 (the first player build asserts it
-in a macOS IL2CPP player and a WebGL player).
+`unity/Assets/Tests/EditMode/SimSmokeTests.cs` runs the same playthroughs inside Unity against `GoldenRun`'s constants
+(run `tools/build_sim_for_unity.sh` first so Unity has the current DLLs).
-**Any change to this hash is a deliberate rules or content change.** Such a change could be to a rule, a system,
-content in `content/`, or the hash format. When it happens, update the constant here, in `DeterminismTests.cs` and in
-`SimSmokeTests.cs`, all in the same commit, and say in the commit message why the hash moved. If the hash changes and
-you did not mean to change rules or content, treat it as a determinism bug.
+Verified on .NET and Unity editor Mono. IL2CPP and WebGL: pending (M3 Task 22 checks both players).
+
+**Any change to a golden hash is a deliberate rules or content change.** Such a change could be to a rule, a system,
+content in `content/`, or the hash format. When it happens, update every place above in the same commit, add a row to
+the history below, and say in the commit message why the hash moved. If a hash changes and you did not mean to change
+rules or content, treat it as a determinism bug.
+
+## Rebaseline history
+
+| Plan task | Run | New hash (first 8) | Why |
+|---|---|---|---|
diff --git a/sim/Statecraft.Sim.Tests/DeterminismTests.cs b/sim/Statecraft.Sim.Tests/DeterminismTests.cs
index 11b7b067b..4b11f8881 100644
--- a/sim/Statecraft.Sim.Tests/DeterminismTests.cs
+++ b/sim/Statecraft.Sim.Tests/DeterminismTests.cs
@@ -1,7 +1,7 @@
using System;
using Statecraft.Sim;
-/// <summary>Fixed reference values for the generator and for one full historical playthrough. See docs/determinism.md.</summary>
+/// <summary>Fixed reference values for the generator and for the golden historical playthroughs. See docs/determinism.md.</summary>
public class DeterminismTests
{
/// <summary>The first three outputs of Vigna's reference splitmix64.c (https://prng.di.unimi.it/splitmix64.c)
@@ -17,25 +17,23 @@ public class DeterminismTests
Assert.Equal(third, rng.NextULong());
}
- /// <summary>Any change to this value is a deliberate rules or content change: update it here and in
- /// docs/determinism.md (and the Unity edit-mode SimSmokeTests) in the same commit.</summary>
+ /// <summary>Any change to this value is a deliberate rules or content change: update it here, in
+ /// GoldenRun.Hash1950 and in docs/determinism.md in the same commit.</summary>
public const string GoldenHash = "eb9756528eeebdc7b078ab90f7fe7a349edcfc94be9543e5f20f258da4e500e9";
/// <summary>Real content, seed 1948, Historical mode, HistoricalAI until the date reaches 1950-01-01.</summary>
- public static GameState GoldenPlaythrough(Content c)
- {
- var s = Simulation.NewGame(c, 1948UL, Mode.Historical);
- for (int turn = 0; turn < 1000 && s.Date < new DateTime(1950, 1, 1) && s.GameOver == null; turn++)
- s = Simulation.Step(c, s, HistoricalAI.Commands(c, s)).State;
- return s;
- }
+ public static GameState GoldenPlaythrough(Content c) => GoldenRun.Play(c, GoldenRun.Until1950);
[Fact]
public void GoldenPlaythroughHashIsFixed()
{
var s = GoldenPlaythrough(ContentLoader.Load(RealContentTests.ContentRoot()));
Assert.Null(s.GameOver);
- Assert.True(s.Date >= new DateTime(1950, 1, 1));
+ Assert.True(s.Date >= GoldenRun.Until1950);
Assert.Equal(GoldenHash, s.Hash());
}
+
+ /// <summary>The library constant Unity players compare against is the value this test pins.</summary>
+ [Fact]
+ public void LibraryGoldenConstantMatchesThisTest() => Assert.Equal(GoldenHash, GoldenRun.Hash1950);
}
diff --git a/sim/Statecraft.Sim.Tests/PeriodValidationTests.cs b/sim/Statecraft.Sim.Tests/PeriodValidationTests.cs
new file mode 100644
index 000000000..9504253b7
--- /dev/null
+++ b/sim/Statecraft.Sim.Tests/PeriodValidationTests.cs
@@ -0,0 +1,81 @@
+using System;
+using System.Collections.Generic;
+using Statecraft.Sim;
+
+/// <summary>Load-time checks that keep "who governed / which body sat / who held office on this date" unambiguous:
+/// no overlapping legislatures or governments, no term in an abolished office, no term after its holder's death.</summary>
+public class PeriodValidationTests
+{
+ [Fact]
+ public void OverlappingLegislaturesAreALoadError()
+ {
+ var ex = ValidationTests.Bad("legislatures.yaml", "to: 1949-02-14", "to: 1949-03-01");
+ Assert.Equal("legislatures.yaml", ex.File);
+ Assert.Equal("legislatures[house].from", ex.Field);
+ Assert.Contains("overlaps council (1948-05-14 to 1949-03-01)", ex.Message);
+ }
+
+ [Fact]
+ public void AnOpenEndedLegislatureFollowedByAnotherIsAnOverlap()
+ {
+ var ex = ValidationTests.Bad("legislatures.yaml", "to: 1949-02-14", "");
+ Assert.Equal("legislatures[house].from", ex.Field);
+ Assert.Contains("overlaps council (1948-05-14 to open)", ex.Message);
+ }
+
+ [Fact]
+ public void OverlappingGovernmentsAreALoadError()
+ {
+ var ex = ValidationTests.Bad("governments.yaml", "to: 1949-03-10", "to: 1949-04-01");
+ Assert.Equal("governments.yaml", ex.File);
+ Assert.Equal("governments[gov2].from", ex.Field);
+ Assert.Contains("overlaps gov1", ex.Message);
+ }
+
+ [Fact]
+ public void AGapBetweenGovernmentsIsAllowed()
+ {
+ var gov = Fixture.Files["governments.yaml"].Replace("to: 1949-03-10", "to: 1949-03-01");
+ var c = ContentLoader.Load(Fixture.Write(new Dictionary<string, string> { ["governments.yaml"] = gov }));
+ Assert.Null(Offices.Government(c, new DateTime(1949, 3, 5)));
+ }
+
+ [Fact]
+ public void ATermRunningPastTheOfficesAbolitionIsALoadError()
+ {
+ var ex = ValidationTests.Bad("offices.yaml", "title: Minister of Finance", "title: Minister of Finance\n until: 1949-01-01");
+ Assert.Equal("people.yaml", ex.File);
+ Assert.Equal("people[def_two].offices.finance_minister.to", ex.Field);
+ Assert.Contains("must be on or before 1949-01-01, when the office was abolished", ex.Message);
+ }
+
+ [Fact]
+ public void AnAbolishedOfficeWhoseTermsEndInTimeLoads()
+ {
+ var offices = Fixture.Files["offices.yaml"].Replace("title: Minister of Finance", "title: Minister of Finance\n until: 1949-01-01");
+ var people = Fixture.Files["people.yaml"].Replace(" - office: finance_minister\n from: 1948-05-14", " - office: finance_minister\n from: 1948-05-14\n to: 1949-01-01");
+ var rules = Fixture.Files["rules.yaml"].Replace("budget_start: { finance_minister: 1.0 }", "budget_start: { prime_minister: 1.0 }");
+ var c = ContentLoader.Load(Fixture.Write(new Dictionary<string, string> { ["offices.yaml"] = offices, ["people.yaml"] = people, ["rules.yaml"] = rules }));
+ Assert.Equal(new DateTime(1949, 1, 1), c.Offices.Find(o => o.Id == "finance_minister")!.Until);
+ Assert.Null(Offices.Holder(c, "finance_minister", new DateTime(1949, 1, 1)));
+ }
+
+ [Fact]
+ public void ABudgetLineForAnAbolishedOfficeIsALoadError()
+ {
+ var offices = Fixture.Files["offices.yaml"].Replace("title: Minister of Finance", "title: Minister of Finance\n until: 1949-01-01");
+ var people = Fixture.Files["people.yaml"].Replace(" - office: finance_minister\n from: 1948-05-14", " - office: finance_minister\n from: 1948-05-14\n to: 1949-01-01");
+ var ex = Assert.Throws<ContentException>(() => ContentLoader.Load(Fixture.Write(new Dictionary<string, string> { ["offices.yaml"] = offices, ["people.yaml"] = people })));
+ Assert.Equal("rules.yaml", ex.File);
+ Assert.Equal("budget_start.finance_minister", ex.Field);
+ Assert.Contains("is abolished on 1949-01-01: give its budget line to the office that took over", ex.Message);
+ }
+
+ [Fact]
+ public void ATermRunningPastTheHoldersDeathIsALoadError()
+ {
+ var ex = ValidationTests.Bad("people.yaml", " name: Def Two\n", " name: Def Two\n died: 1949-06-01\n");
+ Assert.Equal("people[def_two].offices.defense_minister.to", ex.Field);
+ Assert.Contains("must be on or before 1949-06-01, the date of death", ex.Message);
+ }
+}
diff --git a/sim/Statecraft.Sim/Content.cs b/sim/Statecraft.Sim/Content.cs
index 8fbad5136..a855eb672 100644
--- a/sim/Statecraft.Sim/Content.cs
+++ b/sim/Statecraft.Sim/Content.cs
@@ -8,7 +8,13 @@ namespace Statecraft.Sim
public sealed class Source { public string Url { get; set; } = ""; public DateTime Checked { get; set; } }
- public sealed class Office { public string Id { get; set; } = ""; public string Title { get; set; } = ""; }
+ public sealed class Office
+ {
+ public string Id { get; set; } = "";
+ public string Title { get; set; } = "";
+ /// <summary>Day the office was abolished (exclusive end, like a term's `to`); null while it still exists.</summary>
+ public DateTime? Until { get; set; }
+ }
public sealed class Party { public string Id { get; set; } = ""; public string Name { get; set; } = ""; }
@@ -31,6 +37,8 @@ namespace Statecraft.Sim
public string NameHe { get; set; } = "";
/// <summary>Required (null only when missing, which is a load error): a living person is excluded from release builds.</summary>
public bool? Living { get; set; }
+ /// <summary>Date of death, when it falls inside the content range: every term must end by then.</summary>
+ public DateTime? Died { get; set; }
public int Competence { get; set; }
public int Loyalty { get; set; }
public string Party { get; set; } = "";
diff --git a/sim/Statecraft.Sim/ContentLoader.cs b/sim/Statecraft.Sim/ContentLoader.cs
index 4714ff331..29954fec9 100644
--- a/sim/Statecraft.Sim/ContentLoader.cs
+++ b/sim/Statecraft.Sim/ContentLoader.cs
@@ -172,6 +172,21 @@ namespace Statecraft.Sim
if (to.HasValue && to.Value <= from) throw new ContentException(file, path + ".to", FormattableString.Invariant($"must be after from ({from:yyyy-MM-dd})"));
}
+ /// <summary>Only one legislature sits, and one government holds office, on any date: "which body sat on this
+ /// date" must never be ambiguous. Periods are [from, to); sorted by from, each must end on or before the next
+ /// one starts (an open-ended period can only be the last).</summary>
+ static void NoOverlap(string file, string list, IEnumerable<(string id, DateTime from, DateTime? to)> periods)
+ {
+ var sorted = periods.OrderBy(p => p.from).ThenBy(p => p.id, StringComparer.Ordinal).ToList();
+ for (int i = 1; i < sorted.Count; i++)
+ {
+ var (prev, next) = (sorted[i - 1], sorted[i]);
+ if (!prev.to.HasValue || prev.to.Value > next.from)
+ throw new ContentException(file, $"{list}[{next.id}].from", FormattableString.Invariant(
+ $"overlaps {prev.id} ({prev.from:yyyy-MM-dd} to {(prev.to.HasValue ? prev.to.Value.ToString("yyyy-MM-dd", System.Globalization.CultureInfo.InvariantCulture) : "open")})"));
+ }
+ }
+
static void Validate(Content c)
{
var offices = new HashSet<string>(c.Offices.Select(o => o.Id));
@@ -213,6 +228,15 @@ namespace Statecraft.Sim
if (t.To.HasValue && t.To.Value <= t.From) throw new ContentException("people.yaml", $"people[{p.Id}].offices.{t.Office}", FormattableString.Invariant($"term ends ({t.To:yyyy-MM-dd}) before it starts ({t.From:yyyy-MM-dd})"));
}
}
+ foreach (var o in c.Offices.Where(o => o.Until.HasValue))
+ foreach (var p in c.People)
+ foreach (var t in p.Offices.Where(t => t.Office == o.Id))
+ if (!t.To.HasValue || t.To.Value > o.Until!.Value)
+ throw new ContentException("people.yaml", $"people[{p.Id}].offices.{o.Id}.to", FormattableString.Invariant($"must be on or before {o.Until:yyyy-MM-dd}, when the office was abolished"));
+ foreach (var p in c.People.Where(p => p.Died.HasValue))
+ foreach (var t in p.Offices)
+ if (!t.To.HasValue || t.To.Value > p.Died!.Value)
+ throw new ContentException("people.yaml", $"people[{p.Id}].offices.{t.Office}.to", FormattableString.Invariant($"must be on or before {p.Died:yyyy-MM-dd}, the date of death"));
foreach (var p in c.People)
for (int i = 0; i < p.Offices.Count; i++)
for (int j = i + 1; j < p.Offices.Count; j++)
@@ -248,6 +272,8 @@ namespace Statecraft.Sim
foreach (var p in g.Coalition)
if (!parties.Contains(p)) throw new ContentException("governments.yaml", $"governments[{g.Id}].coalition.{p}", "unknown party");
}
+ NoOverlap("legislatures.yaml", "legislatures", c.Legislatures.Select(l => (l.Id, l.From, l.To)));
+ NoOverlap("governments.yaml", "governments", c.Governments.Select(g => (g.Id, g.From, g.To)));
foreach (var i in c.Indicators)
{
Finite("model.yaml", $"indicators[{i.Id}].base", i.Base);
@@ -311,6 +337,11 @@ namespace Statecraft.Sim
foreach (var kv in r.BudgetStart)
{
if (!offices.Contains(kv.Key)) throw new ContentException("rules.yaml", $"budget_start.{kv.Key}", "unknown office");
+ // A budget line must not silently stop mattering when its office is abolished: move it to the office that
+ // took over (plan amendment C3).
+ var until = c.Offices.First(o => o.Id == kv.Key).Until;
+ if (until.HasValue)
+ throw new ContentException("rules.yaml", $"budget_start.{kv.Key}", FormattableString.Invariant($"office '{kv.Key}' is abolished on {until:yyyy-MM-dd}: give its budget line to the office that took over"));
Unit("rules.yaml", $"budget_start.{kv.Key}", kv.Value);
}
// The same rule EconomySystem.Allocate applies to every later allocation.
diff --git a/sim/Statecraft.Sim/GoldenRun.cs b/sim/Statecraft.Sim/GoldenRun.cs
new file mode 100644
index 000000000..cf06e72ab
--- /dev/null
+++ b/sim/Statecraft.Sim/GoldenRun.cs
@@ -0,0 +1,28 @@
+using System;
+
+namespace Statecraft.Sim
+{
+ /// <summary>The reference playthroughs that pin determinism (docs/determinism.md): real content, seed 1948,
+ /// Historical mode, HistoricalAI until the date reaches the given day. The constants live in the sim library so
+ /// Unity players (Golden check) and the editor tests compare against the same values .NET asserts.</summary>
+ public static class GoldenRun
+ {
+ public const ulong Seed = 1948;
+
+ /// <summary>Final hash of Play(content, Until1950). Changing it is a deliberate rules or content change:
+ /// update it, DeterminismTests and docs/determinism.md in the same commit and say why in the message.</summary>
+ public const string Hash1950 = "eb9756528eeebdc7b078ab90f7fe7a349edcfc94be9543e5f20f258da4e500e9";
+
+ public static readonly DateTime Until1950 = new DateTime(1950, 1, 1);
+
+ /// <summary>Steps with HistoricalAI until Date >= <paramref name="until"/>, the game ends, or 1000 turns pass.</summary>
+ public static GameState Play(Content c, DateTime until)
+ {
+ if (c == null) throw new ArgumentNullException(nameof(c));
+ var s = Simulation.NewGame(c, Seed, Mode.Historical);
+ for (int turn = 0; turn < 1000 && s.Date < until && s.GameOver == null; turn++)
+ s = Simulation.Step(c, s, HistoricalAI.Commands(c, s)).State;
+ return s;
+ }
+ }
+}
diff --git a/unity/Assets/Tests/EditMode/SimSmokeTests.cs b/unity/Assets/Tests/EditMode/SimSmokeTests.cs
index 3b67ee894..70c3e1260 100644
--- a/unity/Assets/Tests/EditMode/SimSmokeTests.cs
+++ b/unity/Assets/Tests/EditMode/SimSmokeTests.cs
@@ -17,20 +17,14 @@ public class SimSmokeTests
Assert.IsNotEmpty(ra.State.Hash());
}
- /// <summary>The same playthrough and constant as sim/Statecraft.Sim.Tests/DeterminismTests.cs (see docs/determinism.md).
- /// It proves the Unity editor's runtime computes, bit for bit, what .NET computes: verified on .NET and Unity editor
- /// Mono; IL2CPP/WebGL pending M3. Update all three places together.</summary>
- public const string GoldenHash = "eb9756528eeebdc7b078ab90f7fe7a349edcfc94be9543e5f20f258da4e500e9";
-
+ /// <summary>The golden playthroughs of docs/determinism.md, run on the Unity editor's Mono runtime. The constants are
+ /// GoldenRun's, which sim/Statecraft.Sim.Tests/DeterminismTests.cs pins on .NET; rebuild the DLLs
+ /// (tools/build_sim_for_unity.sh) after changing them.</summary>
[Test]
- public void GoldenPlaythroughMatchesDotNet()
+ public void GoldenPlaythroughTo1950MatchesDotNet()
{
- var c = ContentLoader.Load(Paths.Content);
- var s = Simulation.NewGame(c, 1948UL, Mode.Historical);
- for (int turn = 0; turn < 1000 && s.Date < new System.DateTime(1950, 1, 1) && s.GameOver == null; turn++)
- s = Simulation.Step(c, s, HistoricalAI.Commands(c, s)).State;
+ var s = GoldenRun.Play(ContentLoader.Load(Paths.Content), GoldenRun.Until1950);
Assert.IsNull(s.GameOver);
- Assert.GreaterOrEqual(s.Date, new System.DateTime(1950, 1, 1));
- Assert.AreEqual(GoldenHash, s.Hash());
+ Assert.AreEqual(GoldenRun.Hash1950, s.Hash());
}
}