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.

fix(sim): saves keep text not caller objects; unknown command types refused at Step; ordinal unknown-office reason; Mono UTF-8 test

eyalgolan4abb0c9afd00
diff --git a/sim/Statecraft.Sim.Tests/SaveGameTests.cs b/sim/Statecraft.Sim.Tests/SaveGameTests.cs
index f9006f335..b49345da9 100644
--- a/sim/Statecraft.Sim.Tests/SaveGameTests.cs
+++ b/sim/Statecraft.Sim.Tests/SaveGameTests.cs
@@ -375,4 +375,44 @@ public class SaveGameTests
Assert.Empty(warnings);
Assert.Throws<SaveException>(() => SaveGame.Parse(text.Replace("\n", "\r")));
}
+
+ sealed class Foreign : Command { public override string Kind => "set_policy"; }
+
+ [Fact]
+ public void AForeignCommandNeverMakesTheSaveUnwritable()
+ {
+ var g = GameSession.New(Fixture1(), 1, Mode.Historical);
+ Assert.Throws<ArgumentException>(() => g.Step(new Command[] { new Foreign() }));
+ g.Step(new Command[0]);
+ Assert.StartsWith("statecraft-save 1", g.Save.Write());
+ Assert.Single(g.Save.Turns);
+ }
+
+ [Fact]
+ public void MutatingWhatTurnsReturnsDoesNotChangeTheSave()
+ {
+ var c = Fixture1();
+ var g = GameSession.New(c, 1, Mode.Historical);
+ g.Step(new Command[] { new AllocateBudget(new Dictionary<string, double> { ["finance_minister"] = 0.6, ["defense_minister"] = 0.4 }) });
+ var before = g.Save.Write();
+ var turn = g.Save.Turns[0];
+ ((AllocateBudget)turn[0]).Shares.Clear(); // probe 1: the shares of a recorded order
+ // probe 2: the lists themselves are read-only
+ Assert.Throws<NotSupportedException>(() => ((IList<Command>)turn).Clear());
+ Assert.Throws<NotSupportedException>(() => ((IList<IReadOnlyList<Command>>)g.Save.Turns).Clear());
+ Assert.Equal(before, g.Save.Write());
+ Assert.Single(g.Save.Turns);
+ Assert.Equal(g.State.Hash(), GameSession.Load(c, g.Save.Write(), out _).State.Hash());
+ }
+
+ [Fact]
+ public void TheFirstUnknownOfficeInOrdinalOrderIsNamedInPlayAndInReplay()
+ {
+ var c = Fixture1();
+ var g = GameSession.New(c, 1, Mode.Historical);
+ g.Step(new Command[] { new AllocateBudget(new Dictionary<string, double> { ["zzz"] = 0.5, ["aaa"] = 0.5 }) });
+ var live = g.Last!.Rejected.Single().Reason;
+ Assert.Equal("Unknown office 'aaa'", live);
+ Assert.Equal(live, GameSession.Load(c, g.Save.Write(), out _).Last!.Rejected.Single().Reason);
+ }
}
diff --git a/sim/Statecraft.Sim.Tests/SimTests.cs b/sim/Statecraft.Sim.Tests/SimTests.cs
index c6889126b..24796e491 100644
--- a/sim/Statecraft.Sim.Tests/SimTests.cs
+++ b/sim/Statecraft.Sim.Tests/SimTests.cs
@@ -138,13 +138,14 @@ options:
sealed class Bogus : Command { public override string Kind => "bogus"; }
+ /// <summary>A Command type this assembly does not know cannot be saved, so Step refuses it up front (a programmer error,
+ /// like a null command) instead of rejecting it and leaving a game whose save cannot be written.</summary>
[Fact]
- public void UnknownCommandKindIsRejectedNotThrown()
+ public void ACommandTypeTheSimDoesNotKnowIsRefusedBeforeAnythingRuns()
{
var s0 = Simulation.NewGame(C, 42, Mode.Historical);
- var r = Simulation.Step(C, s0, new Command[] { new Bogus(), new SetMobilization(1.0) });
- Assert.Equal(new[] { "Unknown command 'bogus'" }, r.Rejected.Select(x => x.Reason));
- Assert.Equal(1.0, r.State.Mobilization); // the bogus command cost no attention
+ var ex = Assert.Throws<ArgumentException>(() => Simulation.Step(C, s0, new Command[] { new SetMobilization(1.0), new Bogus() }));
+ Assert.Contains("unknown command type", ex.Message);
}
[Fact]
diff --git a/sim/Statecraft.Sim/Commands.cs b/sim/Statecraft.Sim/Commands.cs
index 81e2087ef..a8f681499 100644
--- a/sim/Statecraft.Sim/Commands.cs
+++ b/sim/Statecraft.Sim/Commands.cs
@@ -86,6 +86,8 @@ namespace Statecraft.Sim
case ChooseEventOption e: Text(e.EventId, "EventId"); Text(e.OptionId, "OptionId"); break;
case Appoint a: Text(a.Office, "Office"); Text(a.Person, "Person"); break;
case MapAction m: Text(m.Action, "Action"); break;
+ case SetMobilization _: case SecurityOrder _: break;
+ default: throw new ArgumentException("unknown command type " + cmd.GetType().Name, "commands");
}
}
diff --git a/sim/Statecraft.Sim/EconomySystem.cs b/sim/Statecraft.Sim/EconomySystem.cs
index fdf7db99b..9c98e7d01 100644
--- a/sim/Statecraft.Sim/EconomySystem.cs
+++ b/sim/Statecraft.Sim/EconomySystem.cs
@@ -55,7 +55,7 @@ namespace Statecraft.Sim
public static string? Allocate(Content c, GameState s, Dictionary<string, double> shares)
{
if (shares == null) return "Budget shares are required";
- var unknown = shares.Keys.FirstOrDefault(k => c.Offices.All(o => o.Id != k));
+ var unknown = shares.Keys.OrderBy(k => k, StringComparer.Ordinal).FirstOrDefault(k => c.Offices.All(o => o.Id != k)); // ordinal: play and replay name the same office
if (unknown != null) return $"Unknown office '{unknown}'";
if (shares.Values.Any(v => double.IsNaN(v) || double.IsInfinity(v))) return "Budget shares must be finite numbers";
if (!new HashSet<string>(shares.Keys).SetEquals(c.Rules.BudgetStart.Keys))
diff --git a/sim/Statecraft.Sim/SaveGame.cs b/sim/Statecraft.Sim/SaveGame.cs
index 61fe95d38..72fc225e0 100644
--- a/sim/Statecraft.Sim/SaveGame.cs
+++ b/sim/Statecraft.Sim/SaveGame.cs
@@ -32,12 +32,16 @@ namespace Statecraft.Sim
public const int MaxTurns = 2000;
const string Magic = "statecraft-save";
- readonly List<IReadOnlyList<Command>> turns = new List<IReadOnlyList<Command>>();
+ /// <summary>Each turn as its canonical command lines. The save keeps text, not the caller's objects, so nothing
+ /// outside can change a recorded turn; <see cref="Turns"/> parses fresh copies on demand.</summary>
+ readonly List<List<string>> turns = new List<List<string>>();
public string ContentHash { get; }
public ulong Seed { get; }
public Mode Mode { get; }
- public IReadOnlyList<IReadOnlyList<Command>> Turns => turns;
+ /// <summary>The recorded turns as new command objects each time it is read (changing them changes nothing in the save).</summary>
+ public IReadOnlyList<IReadOnlyList<Command>> Turns =>
+ turns.Select(t => (IReadOnlyList<Command>)t.Select(l => ParseCommand(0, l)).ToList().AsReadOnly()).ToList().AsReadOnly();
/// <summary>GameState.Hash() after the last recorded turn (the new game's hash before any turn).</summary>
public string FinalHash { get; private set; }
@@ -54,7 +58,7 @@ namespace Statecraft.Sim
if (commands == null) throw new ArgumentNullException(nameof(commands));
if (after == null) throw new ArgumentNullException(nameof(after));
// A recorded turn is immutable: the caller keeps its own objects (an AllocateBudget's dictionary is theirs to reuse).
- turns.Add(commands.Select(Snapshot).ToList());
+ turns.Add(commands.Select(Format).ToList());
FinalHash = after.Hash();
}
@@ -68,15 +72,12 @@ namespace Statecraft.Sim
foreach (var t in turns)
{
sb.Append("turn\n");
- foreach (var cmd in t) sb.Append(Format(cmd)).Append('\n');
+ foreach (var line in t) sb.Append(line).Append('\n');
}
sb.Append("end ").Append(FinalHash).Append('\n');
return sb.ToString();
}
- static Command Snapshot(Command cmd) =>
- cmd is AllocateBudget b && b.Shares != null ? new AllocateBudget(new Dictionary<string, double>(b.Shares)) : cmd;
-
static string Esc(string s) => SaveText.Escape(s);
static string Num(double v) => BitConverter.DoubleToInt64Bits(v).ToString("X16", CultureInfo.InvariantCulture);
static string Int(int v) => v.ToString(CultureInfo.InvariantCulture);
@@ -125,12 +126,12 @@ namespace Statecraft.Sim
var end = Head(n - 1, "end", 2)[1];
if (!IsHash(end)) throw new SaveException(n, "bad end hash");
var save = new SaveGame(content, seed, mode, end);
- List<Command>? current = null;
+ List<string>? current = null;
for (int i = 4; i < n - 1; i++)
{
- if (lines[i] == "turn") { current = new List<Command>(); save.turns.Add(current); continue; }
+ if (lines[i] == "turn") { current = new List<string>(); save.turns.Add(current); continue; }
if (current == null) throw new SaveException(i + 1, "command before the first 'turn'");
- current.Add(ParseCommand(i + 1, lines[i]));
+ current.Add(Format(ParseCommand(i + 1, lines[i]))); // canonical form, validated now
}
return save;
}
diff --git a/unity/Assets/Tests/EditMode/SimSmokeTests.cs b/unity/Assets/Tests/EditMode/SimSmokeTests.cs
index a2025dc5c..5a9713878 100644
--- a/unity/Assets/Tests/EditMode/SimSmokeTests.cs
+++ b/unity/Assets/Tests/EditMode/SimSmokeTests.cs
@@ -35,4 +35,24 @@ public class SimSmokeTests
Assert.IsNull(s.GameOver);
Assert.AreEqual(GoldenRun.Hash1952, s.Hash());
}
+
+ /// <summary>The save format's strict UTF-8 decoding, on the Unity editor's Mono runtime (it must not depend on the
+ /// BCL's Uri class): an overlong escape is refused, a surrogate pair round-trips.</summary>
+ [Test]
+ public void SaveTextIsStrictUtf8OnMono()
+ {
+ var hash = new string('a', 64);
+ var overlong = "statecraft-save 1\ncontent " + hash + "\nseed 1\nmode Historical\nturn\npolicy a%C0%AF 3FE0000000000000\nend " + hash + "\n";
+ var ex = Assert.Throws<SaveException>(() => SaveGame.Parse(overlong));
+ Assert.AreEqual("line 6: bad text 'a%C0%AF'", ex.Message);
+
+ var content = ContentLoader.Load(Paths.Content);
+ var g = GameSession.New(content, 1UL, Mode.Historical);
+ g.Step(new List<Command> { new SetPolicy("a\uD83D\uDE00b", 1.0) });
+ var text = g.Save.Write();
+ StringAssert.Contains("policy a%F0%9F%98%80b 3FF0000000000000", text);
+ var loaded = GameSession.Load(content, text, out _);
+ Assert.AreEqual(g.State.Hash(), loaded.State.Hash());
+ Assert.AreEqual(text, loaded.Save.Write());
+ }
}