A Civilization-style strategy game about governing Israel from 15 May 1948. Real ministers, real map, every fact sourced. Unity + deterministic C# sim.
Sim: under gdd-0.3, the balance catalogue refuses bad numbers at load (#2372)
Eyal Golanb4ad78f43205
diff --git a/changelog.d/gdd03-balance-number-checks.md b/changelog.d/gdd03-balance-number-checks.mdnew file mode 100644index 000000000..9182b29ee--- /dev/null+++ b/changelog.d/gdd03-balance-number-checks.md@@ -0,0 +1,5 @@+### Fixed++- Behind the scenes: under GDD 0.3 only, the balance file now refuses bad numbers at load and names the row. Every+ number must be at least 0, except the signed housing condition changes; counts and turns are whole, fractions are+ from 0 to 1, and percentage shares are from 0 to 100. The current game (gdd-0.1) is unchanged.diff --git a/sim/Statecraft.Sim.Tests/DesignValuesGdd03Tests.cs b/sim/Statecraft.Sim.Tests/DesignValuesGdd03Tests.csindex 4d1fba9b7..55f9edf60 100644--- a/sim/Statecraft.Sim.Tests/DesignValuesGdd03Tests.cs+++ b/sim/Statecraft.Sim.Tests/DesignValuesGdd03Tests.cs@@ -269,6 +269,99 @@ public partial class DesignValuesTestsAssert.Equal(1m, Assert.Single(repair.Parts["work"].Values));Assert.Equal(10m, Assert.Single(repair.Parts["condition_pp"].Values));}+ // R-LOOP-005: every numeric gdd-0.3 catalogue row is checked when the authored file loads.+ // Sets one row's values (or one part's), found by its YAML key, whatever its current value or note text says.+ static string WithValues(string yaml, string key, string values, string? part=null)+ {+ var lines=yaml.Split('\n');+ int Single(int from, int to, Func<string,bool> match)+ {+ var hits=Enumerable.Range(from,to-from).Where(i=>match(lines[i].TrimEnd('\r'))).ToList();+ Assert.Single(hits);+ return hits[0];+ }+ int BlockEnd(int start, int indent)+ {+ var i=start+1;+ while (i<lines.Length && (lines[i].Trim().Length==0 || lines[i].Length-lines[i].TrimStart(' ').Length>indent)) i++;+ return i;+ }+ var at=Single(0,lines.Length,l=>l==" \""+key+"\":");+ int from=at+1, to=BlockEnd(at,2), indent=4;+ if (part!=null)+ {+ at=Single(from,to,l=>l==" \""+part+"\":");+ (from,to,indent)=(at+1,BlockEnd(at,6),8);+ }+ var prefix=new string(' ',indent)+"\"values\": [";+ var line=Single(from,to,l=>l.StartsWith(prefix,StringComparison.Ordinal) && l.EndsWith("]",StringComparison.Ordinal));+ lines[line]=prefix+values+"]";+ return string.Join("\n",lines);+ }+ static Dictionary<string,string> Gdd03RulesetFiles(string catalogue)+ {+ var files=Fixture.Gdd(new Dictionary<string,string>{{CatalogueFile,catalogue}});+ files["eras.yaml"]=files["eras.yaml"].Replace("loop: gdd", "loop: gdd, ruleset: gdd-0.3");+ return files;+ }+ static ContentException RefusedNumber(string key, string values)+ {+ var yaml=File.ReadAllText(Path.Combine(RealContentTests.ContentRoot(),CatalogueFile));+ var dir=Fixture.Write(Gdd03RulesetFiles(WithValues(yaml,key,values)));+ return Assert.Throws<ContentException>(()=>ContentLoader.Load(dir));+ }+ [Fact] public void Gdd03LoaderRefusesNegativeCountsAtLoad()+ {+ var ex=RefusedNumber("import.delivery_turns","-1");+ Assert.Equal(CatalogueFile,ex.File); Assert.Equal("values.import.delivery_turns",ex.Field);+ Assert.Contains("must be a whole number >= 0",ex.Message);+ }+ [Fact] public void Gdd03LoaderRefusesNegativePricesAtLoad()+ {+ var ex=RefusedNumber("craft.course_cost","-0.5");+ Assert.Equal(CatalogueFile,ex.File); Assert.Equal("values.craft.course_cost",ex.Field);+ Assert.Contains("must be >= 0",ex.Message);+ }+ [Fact] public void Gdd03LoaderRefusesFractionsOutsideZeroToOneAtLoad()+ {+ var ex=RefusedNumber("start.housing_condition","1.01");+ Assert.Equal(CatalogueFile,ex.File); Assert.Equal("values.start.housing_condition",ex.Field);+ Assert.Contains("must be between 0 and 1",ex.Message);+ }+ [Fact] public void Gdd03LoaderRefusesPercentsOutsideZeroToOneHundredAtLoad()+ {+ var ex=RefusedNumber("immigration.mix","101, 10, 10, 5");+ Assert.Equal(CatalogueFile,ex.File); Assert.Equal("values.immigration.mix",ex.Field);+ Assert.Contains("must be between 0 and 100",ex.Message);+ }+ [Fact] public void Gdd03NumericRulesAllowListedNegativeException()+ {+ var yaml=File.ReadAllText(Path.Combine(RealContentTests.ContentRoot(),CatalogueFile));+ var catalogue=ContentLoader.Load(Fixture.Write(Gdd03RulesetFiles(WithValues(yaml,"permanent_housing","-10","condition_pp")))).Gdd03Balance;+ Assert.NotNull(catalogue);+ Assert.Equal(-10m,Assert.Single(catalogue.Values["permanent_housing"].Parts["condition_pp"].Values));+ }+ [Fact] public void Gdd03NumericRulesAcceptTheRealCatalogueAndEveryListedKeyExists()+ {+ var yaml=File.ReadAllText(Path.Combine(RealContentTests.ContentRoot(),CatalogueFile));+ var files=Fixture.Gdd(new Dictionary<string,string>{{CatalogueFile,yaml}});+ files["eras.yaml"]=files["eras.yaml"].Replace("loop: gdd", "loop: gdd, ruleset: gdd-0.3");+ var catalogue=ContentLoader.Load(Fixture.Write(files)).Gdd03Balance;+ Assert.NotNull(catalogue);+ Assert.Equal(-10m,Assert.Single(catalogue.Values["maabara"].Parts["condition_pp"].Values));+ var listed=Gdd03BalanceCatalogue.NegativeExceptions.Keys+ .Concat(Gdd03BalanceCatalogue.WholeNumberKeys)+ .Concat(Gdd03BalanceCatalogue.FractionKeys)+ .Concat(Gdd03BalanceCatalogue.PercentKeys).ToList();+ Assert.Equal(listed.Count,listed.Distinct(StringComparer.Ordinal).Count());+ foreach (var at in listed) // a misspelt key would silently check nothing+ {+ var path=at.Substring("values.".Length).Split(new[]{".parts."},StringSplitOptions.None);+ var row=catalogue.Values[path[0]];+ if (path.Length==2) row=row.Parts[path[1]];+ Assert.NotEmpty(row.Values);+ }+ }[Theory][InlineData("bad: { basis: Unknown, values: [1], note: test }")][InlineData("bad: { basis: Agreed, values: [1] }")]diff --git a/sim/Statecraft.Sim.Tests/Gdd03MovementFortTests.cs b/sim/Statecraft.Sim.Tests/Gdd03MovementFortTests.csindex 5401d071d..607231696 100644--- a/sim/Statecraft.Sim.Tests/Gdd03MovementFortTests.cs+++ b/sim/Statecraft.Sim.Tests/Gdd03MovementFortTests.cs@@ -244,6 +244,20 @@ public class Gdd03MovementFortTests// Catalogue structural validation still applies, but none of these valid catalogue rows is a consumed old-rule requirement.Assert.NotNull(ContentLoader.Load(Fixture.Write(f)));}++ [Theory]+ [InlineData("military.move_armoured", "basis: Default, values: [1.5], note: fixture")]+ [InlineData("military.fort_bonus", "basis: Default, values: [-1], note: fixture")]+ public void Gdd03NumberRulesRejectInvalidConsumedScalars(string key, string row)+ {+ var f = Files();+ f[Gdd03BalanceCatalogue.FileName] = System.Text.RegularExpressions.Regex.Replace(f[Gdd03BalanceCatalogue.FileName],+ "(?m)^ \"" + System.Text.RegularExpressions.Regex.Escape(key) + "\":\\n(?: .*\\n)*", " \"" + key + "\": { " + row + " }\n");+ var error = Assert.Throws<ContentException>(() => ContentLoader.Load(Fixture.Write(f)));+ Assert.Equal(Gdd03BalanceCatalogue.FileName, error.File);+ Assert.Equal("values." + key, error.Field);+ Assert.Contains("must be a whole number >= 0", error.Message);+ }// R-MOVE-007: both endpoints must belong to the same built segment for either corridor kind.[Theory][InlineData("road")]diff --git a/sim/Statecraft.Sim/ContentLoader.cs b/sim/Statecraft.Sim/ContentLoader.csindex 4562ffb2c..8ec25121e 100644--- a/sim/Statecraft.Sim/ContentLoader.cs+++ b/sim/Statecraft.Sim/ContentLoader.cs@@ -436,6 +436,7 @@ namespace Statecraft.SimValidate(c, settlementIds);if (c.Ruleset == SaveGame.Gdd03Ruleset && c.Gdd03Balance == null)throw new ContentException(Gdd03BalanceCatalogue.FileName, "(file)", "required for the gdd-0.3 ruleset");+ if (c.Ruleset == SaveGame.Gdd03Ruleset) c.Gdd03Balance!.ValidateNumbers();// R-POP-001: validate the identity-specific scale without altering old content reads/hash inputs.if (c.UsesPopulationLedger) _ = c.PopulationPeoplePerUnit;ApplyMapOverrides(readFile, c, settlementIds); // after the map's own checks, before the GDD records that read itdiff --git a/sim/Statecraft.Sim/Gdd03BalanceCatalogue.cs b/sim/Statecraft.Sim/Gdd03BalanceCatalogue.csindex 66f2901e4..3aa467bc2 100644--- a/sim/Statecraft.Sim/Gdd03BalanceCatalogue.cs+++ b/sim/Statecraft.Sim/Gdd03BalanceCatalogue.cs@@ -9,6 +9,63 @@ namespace Statecraft.Sim/// Composite source rows retain separately labelled parts (for example agreed cost, default upkeep).</summary>public sealed class Gdd03BalanceCatalogue{+ // R-LOOP-005: every numeric row is non-negative unless it is one of these signed values. The reasons are part of+ // the exception table so a new exception cannot be added without documenting why it is signed.+ internal static readonly IReadOnlyDictionary<string, string> NegativeExceptions = new Dictionary<string, string>+ {+ ["values.maabara.parts.condition_pp"] = "A signed completion delta; the row note says condition -10 pp.",+ ["values.permanent_housing.parts.condition_pp"] = "A signed completion delta; the row note says condition +10 pp.",+ ["values.housing_repair.parts.condition_pp"] = "A signed completion delta; the row note says condition +10 pp.",+ };++ // Counts, whole turns, movement points, integer draw bands and whole-percent bonuses (no upper bound).+ internal static readonly IReadOnlyCollection<string> WholeNumberKeys = new HashSet<string>(StringComparer.Ordinal)+ {+ "values.campaign.play_minutes", "values.event.max_gap_peace", "values.event.max_gap_war",+ "values.population.people_per_unit", "values.start.population", "values.start.spare_arms",+ "values.start.farmers", "values.start.prepared_fields", "values.start.trained_pioneers",+ "values.start.apprentices", "values.start.experts", "values.start.pioneer_teachers",+ "values.start.military_camps", "values.start.reception_camps", "values.start.training_centres",+ "values.start.industry_slots", "values.start.permanent_housing_projects", "values.start.housing_capacity",+ "values.profession.course_turns", "values.profession.trainees_per_teacher", "values.profession.work_to_veteran",+ "values.craft.course_turns", "values.craft.expert_work_turns", "values.builder.slots_per_project",+ "values.construction.starts_per_turn", "values.field.slots", "values.field.nominal_turns",+ "values.reception.capacity", "values.reception.turns", "values.reception.basic_credit",+ "values.reception.queue_cohesion_loss.parts.cadence_turns", "values.import.delivery_turns",+ "values.immigration.ship_interval", "values.immigration.units_per_ship", "values.workshop.staffed_turns",+ "values.military.camp_capacity", "values.military.basic_turns", "values.military.issue_arms",+ "values.military.draft_wait", "values.military.demobilise_wait", "values.military.demobilise_return",+ "values.military.repeat_issue", "values.military.combat_arms", "values.military.combat_xp_gain",+ "values.military.combat_xp_full", "values.military.fort_bonus", "values.military.fortify_turns",+ "values.military.fortify_bonus", "values.military.stack_limit", "values.military.move_infantry",+ "values.military.move_armoured", "values.military.move_road", "values.military.move_rail",+ "values.military.armistice_quiet_turns", "values.occupation.garrison", "values.occupation.turns",+ "values.combat.draw_count", "values.combat.draw_count.parts.draw_band",+ "values.combat.draw_count.parts.below_0_5", "values.combat.draw_count.parts.from_0_5_below_1",+ "values.combat.draw_count.parts.from_1_below_2", "values.combat.draw_count.parts.at_least_2",+ "values.combat.retreat_hexes", "values.combat.artillery_range", "values.combat.loss_cohorts",+ "values.absorption.population_target", "values.maabara.parts.housing",+ "values.permanent_housing.parts.housing", "values.industry.parts.job_slots",+ "values.arms_workshop.parts.worker_slots", "values.coastal_plain.parts.movement",+ "values.coastal_plain.parts.defence_percent", "values.lowland.parts.movement",+ "values.lowland.parts.defence_percent", "values.valley.parts.movement",+ "values.valley.parts.defence_percent", "values.hills.parts.movement",+ "values.hills.parts.defence_percent", "values.mountains.parts.movement",+ "values.mountains.parts.defence_percent", "values.desert.parts.movement",+ "values.desert.parts.defence_percent",+ };++ internal static readonly IReadOnlyCollection<string> FractionKeys = new HashSet<string>(StringComparer.Ordinal)+ {+ "values.start.housing_condition", "values.housing.condition_max", "values.housing.money_threshold",+ "values.housing.cohesion_threshold", "values.puppet.tax_fraction",+ };++ internal static readonly IReadOnlyCollection<string> PercentKeys = new HashSet<string>(StringComparer.Ordinal)+ {+ "values.immigration.mix", "values.absorption.max_overflow", "values.absorption.min_employment",+ };+public const string FileName = "gdd03-balance.yaml";public string Ruleset { get; set; } = "";public Dictionary<string, Gdd03DesignValue> Values { get; set; } = new Dictionary<string, Gdd03DesignValue>();@@ -32,6 +89,35 @@ namespace Statecraft.Simentry.Value.Validate("values." + entry.Key);}}++ internal void ValidateNumbers()+ {+ foreach (var entry in Values.OrderBy(x => x.Key, StringComparer.Ordinal))+ ValidateNumbers(entry.Value, "values." + entry.Key);+ }++ static void ValidateNumbers(Gdd03DesignValue row, string at)+ {+ ValidateNumbers(at, row.Values);+ foreach (var part in row.Parts.OrderBy(x => x.Key, StringComparer.Ordinal))+ ValidateNumbers(part.Value, at + ".parts." + part.Key);+ }++ static void ValidateNumbers(string at, IEnumerable<decimal> values)+ {+ if (NegativeExceptions.ContainsKey(at)) return;+ foreach (var value in values)+ {+ if (WholeNumberKeys.Contains(at) && (value < 0 || value != decimal.Truncate(value)))+ throw new ContentException(FileName, at, "must be a whole number >= 0");+ if (FractionKeys.Contains(at) && (value < 0 || value > 1))+ throw new ContentException(FileName, at, "must be between 0 and 1");+ if (PercentKeys.Contains(at) && (value < 0 || value > 100))+ throw new ContentException(FileName, at, "must be between 0 and 100");+ if (value < 0)+ throw new ContentException(FileName, at, "must be >= 0");+ }+ }}public sealed class Gdd03DesignValue