From b4702bbc33a209432f948897bbbb1d9327354a6c Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Sat, 19 Sep 2026 04:10:19 +0200 Subject: [PATCH 1/3] Cut 7: continuous consumers brown out instead of flicking off docs/stats-and-power-target.md: "Continuous consumers brown out through a power supply curve on their performance stats." Cut 6 wired the curve (EquippedItem.PowerSupplyFactor) but every continuous consumer still gated its own effect on Item.PowerSupply >= 1f, so an 80% grant produced nothing instead of 80% performance. - Thruster/AetherDrive: gate narrowed from ">= 1f" to a true-zero floor (> 1e-4f, PowerBus's own epsilon); Thrust/Torque are plain Evaluate() reads, so a curved stat already degrades once the full-grant demand is dropped. - Radiator: the gate is deleted outright. PumpedHeat is already a curved Evaluate() read; waste heat is unaffected, so a starved radiator now falls behind instead of refusing to pump, and zero supply already zeroes PumpedHeat via the curve with no special case needed. - ConstantWeapon: the weapon no longer safes itself off (_firing = false) on a partial grant -- only true zero still stops it. Damage already degrades via base.Execute's own Evaluate() read. - EnergyDraw: has no performance stat of its own -- its Execute return value IS the effect (gates its BehaviorGroup). Narrowed the same way: a partial grant still passes, only true zero closes the gate. InputCapacitor and the three instant consumers (InstantWeapon, Sensor, Shield) are untouched: all-or-nothing on a partial charge still holds. Co-Authored-By: Claude Opus 5 --- Assets/Scripts/ServerShared/Behaviors/AetherDrive.cs | 6 ++++-- Assets/Scripts/ServerShared/Behaviors/ConstantWeapon.cs | 6 +++++- Assets/Scripts/ServerShared/Behaviors/EnergyDraw.cs | 9 ++++++++- Assets/Scripts/ServerShared/Behaviors/Radiator.cs | 8 ++++++-- Assets/Scripts/ServerShared/Behaviors/Thruster.cs | 7 ++++++- 5 files changed, 29 insertions(+), 7 deletions(-) diff --git a/Assets/Scripts/ServerShared/Behaviors/AetherDrive.cs b/Assets/Scripts/ServerShared/Behaviors/AetherDrive.cs index 9efa1207b..5baf95eb8 100644 --- a/Assets/Scripts/ServerShared/Behaviors/AetherDrive.cs +++ b/Assets/Scripts/ServerShared/Behaviors/AetherDrive.cs @@ -159,13 +159,15 @@ public class AetherDrive : Behavior, IPowerConsumer Item.SetAudioParameter(_data.RpmAudioParameter, (Rpm.x + Rpm.y + Rpm.z) / 3 / MaximumRpm); Item.SetAudioParameter(_data.TorqueRatioAudioParameter, max(max(torqueRatio.x, torqueRatio.y), torqueRatio.z)); - if (Item.PowerSupply >= 1f) + // Cut 7 (docs/stats-and-power-target.md): actualRpmDelta already derives from Evaluate(_data.Torque) + // above, so a Torque stat carrying a PowerSupply term already shrinks the rotor's spin-up under a + // partial grant -- this no longer demands a full one, only that supply has not been cut to true zero. + if (Item.PowerSupply > 1e-4f) { Rpm += actualRpmDelta; return true; } - return false; } } \ No newline at end of file diff --git a/Assets/Scripts/ServerShared/Behaviors/ConstantWeapon.cs b/Assets/Scripts/ServerShared/Behaviors/ConstantWeapon.cs index 83fddfc52..107b6f847 100644 --- a/Assets/Scripts/ServerShared/Behaviors/ConstantWeapon.cs +++ b/Assets/Scripts/ServerShared/Behaviors/ConstantWeapon.cs @@ -92,7 +92,11 @@ public class ConstantWeapon : Weapon, IProgressBehavior, IEventBehavior, IPowerC } if (_firing) { - if (Item != null && Item.PowerSupply < 1f) + // Cut 7 (docs/stats-and-power-target.md): base.Execute(dt) above already re-read Damage through + // Evaluate(_data.Damage), so a Damage stat carrying a PowerSupply term already fires this tick for + // less under a partial grant -- the weapon no longer safes itself off (the "flicking off gear" bug + // the ruling names) just because the grant fell short of 1. Only true zero supply still stops it. + if (Item != null && Item.PowerSupply <= 1e-4f) { _firing = false; OnStopFiring?.Invoke(); diff --git a/Assets/Scripts/ServerShared/Behaviors/EnergyDraw.cs b/Assets/Scripts/ServerShared/Behaviors/EnergyDraw.cs index ceb535903..ee57853f6 100644 --- a/Assets/Scripts/ServerShared/Behaviors/EnergyDraw.cs +++ b/Assets/Scripts/ServerShared/Behaviors/EnergyDraw.cs @@ -54,6 +54,13 @@ public class EnergyDraw : Behavior, IPowerConsumer // A consumable-hosted instance (Item null) has no PowerBus entry (ยง1.2's grants are keyed by // EquippedItem); named rather than silently assumed away, it always succeeds here, the same way every // other context-dependent factor a ConsumableItemEffect answers with the identity elsewhere in this cut. - return Item == null || Item.PowerSupply >= 1f; + // + // Cut 7 (docs/stats-and-power-target.md): unlike the other four continuous consumers, EnergyDraw has no + // performance stat of its own to curve -- its Execute return value IS its whole effect, the gate that + // decides whether the rest of its BehaviorGroup runs at all (Entity.cs's per-group Execute chain). There + // is nothing here for a PowerSupply term to degrade continuously, so brownout is expressed the only way + // this behaviour can express it: a partial grant still passes (no more flicking off at 80%), and only a + // true zero grant closes the gate. + return Item == null || Item.PowerSupply > 1e-4f; } } \ No newline at end of file diff --git a/Assets/Scripts/ServerShared/Behaviors/Radiator.cs b/Assets/Scripts/ServerShared/Behaviors/Radiator.cs index 868139ef8..d7a9a7c58 100644 --- a/Assets/Scripts/ServerShared/Behaviors/Radiator.cs +++ b/Assets/Scripts/ServerShared/Behaviors/Radiator.cs @@ -86,8 +86,12 @@ public class Radiator : Behavior, IAlwaysUpdatedBehavior, IInitializableBehavior // Temperature ratio would cause more waste heat than pump capacity, stop executing if (tempRatio > PumpedHeat / WasteHeat) return true; - if (Item != null && Item.PowerSupply < 1f) return false; - + // Cut 7 (docs/stats-and-power-target.md): no separate power gate at all. PumpedHeat above is already a + // plain Evaluate() read, so a PumpedHeat stat carrying a PowerSupply term already pumps less under a + // partial grant -- waste heat below is unaffected by the curve, so a starved radiator falls behind and + // the ship heats up, which is the reduced-performance failure the ruling asks for instead of the pump + // simply refusing to run. At true zero supply PumpedHeat itself resolves to 0 (pow(0, exponent) == 0), + // so "produces nothing" already falls out of the curve below without a special case here. var pumpedHeat = PumpedHeat * max(itemTemperature - _data.TemperatureFloor, 0); // Radiator temperature is below temperature floor, stop executing diff --git a/Assets/Scripts/ServerShared/Behaviors/Thruster.cs b/Assets/Scripts/ServerShared/Behaviors/Thruster.cs index b11453137..7236ed5de 100644 --- a/Assets/Scripts/ServerShared/Behaviors/Thruster.cs +++ b/Assets/Scripts/ServerShared/Behaviors/Thruster.cs @@ -83,7 +83,12 @@ public class Thruster : Behavior, IAnalogBehavior, IPowerConsumer public override bool Execute(float dt) { Item.SetAudioParameter(SpecialAudioParameter.Intensity, _input); - if(_input > .01f && Item.PowerSupply >= 1f) + // Cut 7 (docs/stats-and-power-target.md): "continuous consumers brown out ... through a power supply + // curve on their performance stats." Thrust below is a plain Evaluate() read, so once the catalog's own + // Thrust stat carries a PowerSupply term, a partial grant already comes back reduced -- this gate no + // longer demands a full grant, only that the thruster is being asked to do anything (_input) and that it + // has not been cut to true zero supply (the epsilon PowerBus itself already treats as "nothing granted"). + if(_input > .01f && Item.PowerSupply > 1e-4f) { Thrust = Evaluate(_data.Thrust); Entity.Velocity -= Direction.xz * _input * Thrust / Entity.Mass * dt; From e42299858c24eb56c26a250d7d9caba9374f219a Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Sat, 19 Sep 2026 04:10:39 +0200 Subject: [PATCH 2/3] Author a PowerSupply term on the four shipped continuous-performance stats Cut 7's gate removal (previous commit) only has anything to curve if some shipped stat actually declares a PowerSupply term. Checked: none did -- removing the gates would have made brownout invisible (still full performance at any nonzero grant) instead of graceful. Added tools/AetherDb's "brownout-migrate [apply]" command (ShieldMigrate's own dry-run/apply/report shape) and ran it against GameData/Aetheria.cc, authoring exponent-1 (linear, the gentle default) PowerSupply terms on: design behaviour stat before after Arctica RadiatorData pumpedHeat 3 -> 4 Iapyx RadiatorData pumpedHeat 1 -> 2 Large Drive ThrusterData thrust 2 -> 3 OK Disperser RadiatorData pumpedHeat 3 -> 4 Skiron RadiatorData pumpedHeat 1 -> 2 Traction AetherDriveData torque 3 -> 4 cold like my heart RadiatorData pumpedHeat 3 -> 4 deep space burnout ThrusterData thrust 3 -> 4 No shipped ConstantWeaponData record exists yet, so ConstantWeaponData.Damage has nothing to author against; the tool still targets it for whenever one ships. None of the four targeted fields is a power-request field (StatValidation.PowerRequestFields), so this does not trip ValidateNoPowerSupplyOnRequest. Co-Authored-By: Claude Opus 5 --- GameData/Aetheria.cc | 4 +- tools/AetherDb/Program.cs | 94 ++++++++++++++++++++++++++++++++++++++- 2 files changed, 95 insertions(+), 3 deletions(-) diff --git a/GameData/Aetheria.cc b/GameData/Aetheria.cc index b41bf1c97..e4dc75607 100644 --- a/GameData/Aetheria.cc +++ b/GameData/Aetheria.cc @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:fd61a9f35c7c9f96ce15f51b98aa35b68f1cf2d149e1bd8075f1eda86ff045ae -size 12682737 +oid sha256:cfb2c1e79fff9330023de3405ad872e1c46e464b45e7719e86509f148493d85a +size 12682801 diff --git a/tools/AetherDb/Program.cs b/tools/AetherDb/Program.cs index 9a6290bf2..3b17c8b67 100644 --- a/tools/AetherDb/Program.cs +++ b/tools/AetherDb/Program.cs @@ -30,8 +30,9 @@ public static class Program case "settings": return Settings(); case "settings-dump": return SettingsDump(); case "shield-migrate": return ShieldMigrate(args.Contains("apply")); + case "brownout-migrate": return BrownoutMigrate(args.Contains("apply")); default: - Console.WriteLine("commands: census, factions, station-fit, hardpoint-fit, loadout [seed], save, settings, settings-dump, dangling [clear ]... [apply], shield-migrate [apply]"); + Console.WriteLine("commands: census, factions, station-fit, hardpoint-fit, loadout [seed], save, settings, settings-dump, dangling [clear ]... [apply], shield-migrate [apply], brownout-migrate [apply]"); return 1; } } @@ -558,4 +559,95 @@ public static class Program Console.WriteLine($"Landed {changed.Count} changed records in Aetheria.cc"); return 0; } + + // Operator ruling, docs/stats-and-power-target.md: "Continuous consumers brown out through a power supply + // curve on their performance stats." The Cut 7 code change (PowerBus.cs's five continuous-consumer gates) + // only has anything to curve if some shipped stat actually declares a PowerSupply term -- otherwise every + // one of those stats keeps answering PowerSupplyFactor's identity (Entity.cs), and removing the gates makes + // a partial grant read exactly like a full one instead of a reduced one. This authors the term, once, on the + // one performance stat each of the four curve-eligible behaviours (EnergyDraw has none -- see EnergyDraw.cs) + // actually reads for its continuous effect: ThrusterData.Thrust, AetherDriveData.Torque, + // RadiatorData.PumpedHeat, ConstantWeaponData.Damage. None of the four is a power-request field + // (StatValidation.PowerRequestFields), so authoring the term here does not trip + // ValidateNoPowerSupplyOnRequest. Exponent 1 (linear) is the gentle default the ruling calls for -- half + // supply reads as half performance, not a cliff -- and is left for the operator to steepen per design later. + // Dry run unless passed "apply"; every record must derive cleanly or nothing is written, same contract as + // ShieldMigrate. + private static int BrownoutMigrate(bool apply) + { + var db = AetherDb.Open(catalogWritable: apply); + const float gentleExponent = 1f; + + // (behaviour type, target performance-stat field, short label) -- deliberately NOT the request field + // (StatValidation.PowerRequestFields already forbids a PowerSupply term there for each of these types). + var targets = new (Type BehaviorType, string Field, string Label)[] + { + (typeof(ThrusterData), nameof(ThrusterData.Thrust), "thrust"), + (typeof(AetherDriveData), nameof(AetherDriveData.Torque), "torque"), + (typeof(RadiatorData), nameof(RadiatorData.PumpedHeat), "pumpedHeat"), + (typeof(ConstantWeaponData), nameof(WeaponData.Damage), "damage"), + }; + + var hosts = db.Cache.GetAll().Select(g => (Name: g.Name, Document: (object) g, Key: db.Cache.RefOf(g).Key, Behaviors: g.Behaviors)) + .Concat(db.Cache.GetAll().Select(c => (Name: c.Name, Document: (object) c, Key: db.Cache.RefOf(c).Key, Behaviors: c.Behaviors))); + + Console.WriteLine($"{"design",-24} {"behaviour",-14} {"stat",-10} {"before",8} {"after",8} exponent"); + var changed = new List<(object Document, CultRecordKey Key)>(); + var alreadyAuthored = 0; + var failures = 0; + foreach (var (name, document, key, behaviors) in hosts.OrderBy(h => h.Name, StringComparer.Ordinal)) + { + foreach (var behavior in behaviors) + { + foreach (var (behaviorType, field, label) in targets) + { + if (!behaviorType.IsInstanceOfType(behavior)) continue; + PerformanceStat stat; + try + { + stat = behaviorType.GetField(field)?.GetValue(behavior) as PerformanceStat + ?? throw new InvalidOperationException($"{behaviorType.Name}.{field} is not a PerformanceStat field"); + } + catch (Exception e) + { + Console.WriteLine($"FAILED reading {name} {behaviorType.Name}.{field}: {e.Message}"); + failures++; + continue; + } + + if (stat.Terms.Any(t => t.Source == StatSource.PowerSupply)) + { + alreadyAuthored++; + Console.WriteLine($"{name,-24} {behaviorType.Name,-14} {label,-10} {"(already authored, left alone)",-17}"); + continue; + } + + var before = stat.Terms.Count; + stat.Terms.Add(new StatTerm { Source = StatSource.PowerSupply, Exponent = gentleExponent }); + Console.WriteLine($"{name,-24} {behaviorType.Name,-14} {label,-10} {before,8} {stat.Terms.Count,8} {gentleExponent:0.##}"); + changed.Add((document, key)); + } + } + } + + Console.WriteLine($"\n{changed.Count} stats authored a PowerSupply term, {alreadyAuthored} already authored (left alone), {failures} failures"); + if (failures > 0) + { + Console.WriteLine("Refusing to write: at least one record failed to derive cleanly."); + return 1; + } + if (changed.Count == 0) return 0; + if (!apply) + { + Console.WriteLine($"Dry run. Pass \"apply\" to land {changed.Count} changed records."); + return 0; + } + + db.Cache.Commit(batch => + { + foreach (var (document, key) in changed) batch.Upsert(document.GetType(), document, key); + }); + Console.WriteLine($"Landed {changed.Count} changed records in Aetheria.cc"); + return 0; + } } From 7e3016c487939a0a8053f26fe7953f79a9441014 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Sat, 19 Sep 2026 04:11:00 +0200 Subject: [PATCH 3/3] Pin Cut 7's brownout rules: BrownoutTests.cs Pins, for each of the five continuous consumers: a partial grant produces a reduced-not-zero-not-full effect, a full grant is unchanged from today, a zero grant produces nothing, and (Thruster, ConstantWeapon) the degradation follows the authored exponent rather than being linear by accident. EnergyDraw is pinned separately as the one consumer with no performance stat of its own -- its Execute return value is the whole effect. A regression Fact pins that InputCapacitor's all-or-nothing rule for instant items (Cut 4) is untouched. Each rule has a matching mutation in tests/mutation_tests_stats_power_cut7.py (modeled on mutation_tests_stats_power_cut6.py's own shape); all eight mutations, including the no-op control, behave as declared. Co-Authored-By: Claude Opus 5 --- tests/Aetheria.Shared.Tests/BrownoutTests.cs | 352 +++++++++++++++++++ tests/mutation_tests_stats_power_cut7.py | 204 +++++++++++ 2 files changed, 556 insertions(+) create mode 100644 tests/Aetheria.Shared.Tests/BrownoutTests.cs create mode 100644 tests/mutation_tests_stats_power_cut7.py diff --git a/tests/Aetheria.Shared.Tests/BrownoutTests.cs b/tests/Aetheria.Shared.Tests/BrownoutTests.cs new file mode 100644 index 000000000..c90330721 --- /dev/null +++ b/tests/Aetheria.Shared.Tests/BrownoutTests.cs @@ -0,0 +1,352 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using CultMath; +using GameCult.Caching; +using Xunit; +using static CultMath.math; + +// Cut 7 (docs/stats-and-power-target.md): "Continuous consumers brown out through a power supply curve on +// their performance stats. An exponent is enough." Cut 6 wired the curve itself (PowerCurveTests.cs) and the +// bus already writes a real fractional grant (PowerBusTests.cs, PowerTierTests.cs), but every continuous +// consumer still gated its own effect on Item.PowerSupply >= 1f (Thruster.Execute, AetherDrive.Execute, +// Radiator.Execute, ConstantWeapon.Execute, EnergyDraw.Execute) -- so a partial grant read exactly like none, +// the flicking-off bug the ruling names. This file pins each behaviour's own gate removal: a partial grant now +// produces a reduced effect, a full grant is unchanged, a zero grant still produces nothing, the degradation +// follows the authored exponent (not accidentally linear), and an instant item (InputCapacitor's all-or-nothing +// rule, Cut 4) is untouched by any of it. Each rule has a matching mutation in +// tests/mutation_tests_stats_power_cut7.py. +public sealed class BrownoutTests : IDisposable +{ + private readonly string _root = Path.Combine(Path.GetTempPath(), "aetheria-brownout-" + Guid.NewGuid().ToString("N")); + private string Catalog => Path.Combine(_root, "Aetheria.cc"); + + public BrownoutTests() => Directory.CreateDirectory(_root); + public void Dispose() => Directory.Delete(_root, true); + + private static GameplaySettings Settings() => new GameplaySettings + { + DefaultEntitySettings = new EntitySettings(), + Tiers = new[] { new RarityTier { Name = "Common", Quality = .5f, Rarity = 0, Color = new float3(1, 1, 1) } }, + QualityPriceModifier = new ExponentialLerp() + }; + + private static PerformanceStat Constant(float v) => new PerformanceStat { Min = v, Max = v }; + + // Min=0 (not Min=Max like Constant) is the point: a term can only ever be observed to degrade something + // when the stat actually has room to move between its floor and its authored ceiling. + private static PerformanceStat Curved(float max, float exponent) => + new PerformanceStat { Min = 0, Max = max, Terms = { new StatTerm { Source = StatSource.PowerSupply, Exponent = exponent } } }; + + // A flat Bezier (two keys, equal value, zero tangents): AetherDrive's TorqueProfile multiplies potential + // torque by this curve's value at the current rpm ratio -- flat at 1 keeps that multiplier out of the way of + // the PowerSupply curve under test. + private static BezierCurve FlatCurve(float value) => new BezierCurve + { + Keys = new[] { new float4(0, value, 0, 0), new float4(1, value, 0, 0) } + }; + + private static EquippableItem Mint(CultCache cache, ItemManager items, ItemData design) => new EquippableItem + { + Data = cache.RefOf(design), + Durability = design is EquippableItemData equippable ? equippable.Durability : 0, + Lot = items.Lots.Add(new Lot { Design = cache.RefOf(design), Origin = new Attributed(), Quality = .5f, Roles = new List() }) + }; + + // PowerBusTests/PowerCurveTests' own fixture: a 5x5 hull, a Reactor with no capacitor on the ship (so this + // tick's grant ratio is a clean min(1, generation/demand), nothing smoothed by stored charge), and one named + // consumer behaviour under test. + private CultCache OpenCatalog(BehaviorData consumer) + { + var cache = AetheriaStores.Open(Catalog, catalogWritable: true); + cache.Upsert(new TestCatalogGlobal { Name = "Temperament" }); + var hullShape = new Shape(5, 5); + foreach (var cell in hullShape.AllCoordinates) hullShape[cell] = true; + cache.Upsert(new HullData { Name = "Skiff", HullType = HullType.Ship, Shape = hullShape, Durability = 10, Mass = 1000 }); + cache.Upsert(new GearData + { + Name = "Reactor", Hardpoint = HardpointType.Tool, Shape = new Shape(), Durability = 10, + MinimumTemperature = 0, MaximumTemperature = 1000, OptimalTemperature = 280, PlateauWidth = 400, + Behaviors = { new ReactorData + { + Charge = Constant(0), Efficiency = Constant(1), OverloadEfficiency = Constant(1), ThrottlingFactor = Constant(2) + } } + }); + cache.Upsert(new GearData + { + Name = "Consumer", Hardpoint = HardpointType.Tool, Shape = new Shape(), Durability = 10, + MinimumTemperature = 0, MaximumTemperature = 1000, OptimalTemperature = 280, PlateauWidth = 400, + Behaviors = { consumer } + }); + cache.FlushAsync().Wait(); + return cache; + } + + private Ship BuildShip(CultCache cache, float reactorCharge) + { + var items = new ItemManager(cache, new ProvenanceLedger(), Settings(), _ => { }); + var zone = new Zone(items, new PlanetSettings(), new ZonePack(), new GalaxyZone { Name = "Test Zone", Owner = null }, null); + var hull = Mint(cache, items, cache.GetByName("Skiff")); + var ship = new Ship(items, zone, hull, new EntitySettings()); + + var reactorData = cache.GetByName("Reactor"); + ((ReactorData) reactorData.Behaviors[0]).Charge = Constant(reactorCharge); + Assert.True(ship.TryEquip(Mint(cache, items, reactorData))); + Assert.True(ship.TryEquip(Mint(cache, items, cache.GetByName("Consumer")))); + + zone.Entities.Add(ship); + // A ship already "looking" the way Direction already points keeps Ship.Update's own steering pass a + // no-op (deltaRot == 0): no NaN from an unset LookDirection propagating into AetherDrive's Axis.z, and + // no incidental torque thrust from the ship trying to turn toward a look direction none of these tests + // care about. + ship.LookDirection = float3(0, 0, 1); + ship.Activate(); + return ship; + } + + // --- Thruster: a reverse thruster (default EquippableItem.Rotation == None) driven by MovementDirection.y + // --- (Ship.cs's own axis pass), producing a measurable, unidirectional velocity change with no rotation + // --- component to disentangle (Velocity is updated from the pre-rotation Direction within the same tick). --- + private (float velocityDelta, Thruster thruster) RunThruster(float reactorCharge, float exponent = 1) + { + using var cache = OpenCatalog(new ThrusterData + { + Thrust = Curved(100, exponent), Visibility = Constant(0), Heat = Constant(0), EnergyUsage = Constant(100) + }); + var ship = BuildShip(cache, reactorCharge); + ship.MovementDirection = float2(0, -1); // reverse-thruster axis += -MovementDirection.y == 1 + ship.Update(1f); + return (-ship.Velocity.y, ship.GetBehavior()); + } + + [Fact] + public void ThrusterAtHalfGrantProducesReducedNotZeroNotFullThrust() + { + var (full, _) = RunThruster(reactorCharge: 1000); // demand 100, generation far exceeds it -> ratio 1 + var (half, _) = RunThruster(reactorCharge: 50); // demand 100, generation 50 -> ratio .5 + + Assert.True(half > 0f && half < full, $"half={half} should sit strictly between 0 and full={full}"); + } + + [Fact] + public void ThrusterAtFullGrantIsUnchangedFromToday() + { + var (full, thruster) = RunThruster(reactorCharge: 1000); + Assert.Equal(1f, thruster.Item.PowerSupply, 3); + Assert.Equal(.1f, full, 3); // 100 thrust / 1000 mass * dt 1, exactly as it read before this cut + } + + [Fact] + public void ThrusterAtZeroGrantProducesNothing() + { + var (zero, thruster) = RunThruster(reactorCharge: 0); + Assert.Equal(0f, thruster.Item.PowerSupply, 3); + Assert.Equal(0f, zero, 3); + } + + // --- The degradation must follow the authored exponent, not the linear response a careless "just multiply + // --- by PowerSupply" implementation (or a mutation dropping the exponent) would produce. Mirrors + // --- PowerCurveTests' own exponent-2 bullet, but through a real gated behaviour instead of an inert stat. --- + [Fact] + public void ThrusterAtHalfGrantDegradesByItsAuthoredExponentNotLinearly() + { + var (half, _) = RunThruster(reactorCharge: 50, exponent: 2); + // Thrust = lerp(0, 100, pow(.5, 2)) = 25; velocity delta = 25 / 1000 mass * dt 1 = .025, not the + // linear-response .05 a dropped exponent would produce. + Assert.Equal(.025f, half, 3); + } + + // --- AetherDrive: PassiveCoupling = 1 engages the rotor regardless of axis input, so the drive can be + // --- exercised without threading Ship's own movement/torque classification -- Axis stays at Ship.Update's + // --- own default (0,0,deltaRot), and deltaRot is 0 by BuildShip's own LookDirection setup. Rpm starts at 0, + // --- so decay(0, ...) contributes nothing and the whole tick's Rpm gain is exactly this behaviour's own + // --- spin-up under test. --- + private (float rpmGain, AetherDrive drive) RunAetherDrive(float reactorCharge, float exponent = 1) + { + using var cache = OpenCatalog(new AetherDriveData + { + RotorDiameter = float3(1, 1, 1), RotorMass = float3(1, 1, 1), + MaximumRpm = Constant(100), CouplingLambda = float3(1, 1, 1), LambdaMultiplier = Constant(1), + CouplingEfficiency = Constant(1), Torque = Curved(30, exponent), TorqueProfile = FlatCurve(1), + EnergyDraw = Constant(50), PassiveCoupling = Constant(1) + }); + var ship = BuildShip(cache, reactorCharge); + ship.Update(1f); + var drive = ship.GetBehavior(); + return (drive.Rpm.x, drive); + } + + [Fact] + public void AetherDriveAtHalfGrantProducesReducedNotZeroNotFullSpinUp() + { + var (full, _) = RunAetherDrive(reactorCharge: 1000); // demand ~50, generation far exceeds it -> ratio 1 + var (half, _) = RunAetherDrive(reactorCharge: 25); // demand ~50, generation 25 -> ratio .5 + + Assert.True(half > 0f && half < full, $"half={half} should sit strictly between 0 and full={full}"); + } + + [Fact] + public void AetherDriveAtFullGrantIsUnchangedFromToday() + { + var (full, drive) = RunAetherDrive(reactorCharge: 1000); + Assert.Equal(1f, drive.Item.PowerSupply, 3); + Assert.True(full > 0f); + } + + [Fact] + public void AetherDriveAtZeroGrantProducesNothing() + { + var (zero, drive) = RunAetherDrive(reactorCharge: 0); + Assert.Equal(0f, drive.Item.PowerSupply, 3); + Assert.Equal(0f, zero, 4); + } + + // --- Radiator: no explicit power gate survives Cut 7 at all -- PumpedHeat above is a plain Evaluate() read, + // --- so a curved PumpedHeat already pumps less under a partial grant, and waste heat is unaffected, so a + // --- starved radiator falls behind (the reduced-performance failure the ruling asks for) instead of the + // --- pump simply refusing to run. Measured via RadiatorTemperature's own rise, which is exactly + // --- pumpedHeat / ThermalMass * dt. --- + private (float temperatureDelta, Radiator radiator) RunRadiator(float reactorCharge, float exponent = 1) + { + using var cache = OpenCatalog(new RadiatorData + { + Emissivity = Constant(0), PumpedHeat = Curved(10, exponent), TemperatureFloor = 0, + WasteHeat = Constant(.1f), EnergyUsage = Constant(50), ThermalMass = Constant(1000) + }); + var ship = BuildShip(cache, reactorCharge); + var radiator = ship.GetBehavior(); + var before = radiator.RadiatorTemperature; + ship.Update(1f); + return (radiator.RadiatorTemperature - before, radiator); + } + + [Fact] + public void RadiatorAtHalfGrantPumpsReducedNotZeroNotFullHeat() + { + var (full, _) = RunRadiator(reactorCharge: 1000); // demand 50, generation far exceeds it -> ratio 1 + var (half, _) = RunRadiator(reactorCharge: 25); // demand 50, generation 25 -> ratio .5 + + Assert.True(half > 0f && half < full, $"half={half} should sit strictly between 0 and full={full}"); + } + + [Fact] + public void RadiatorAtFullGrantIsUnchangedFromToday() + { + var (full, radiator) = RunRadiator(reactorCharge: 1000); + Assert.Equal(1f, radiator.Item.PowerSupply, 3); + Assert.True(full > 0f); + } + + [Fact] + public void RadiatorAtZeroGrantProducesNothing() + { + var (zero, radiator) = RunRadiator(reactorCharge: 0); + Assert.Equal(0f, radiator.Item.PowerSupply, 3); + Assert.Equal(0f, zero, 4); + } + + // --- ConstantWeapon: the exact bug the ruling names -- a partial grant used to safe the weapon off + // --- entirely (_firing = false), not merely fire it for less. base.Execute(dt) re-reads Damage through + // --- Evaluate() every tick regardless of _firing, so a curved Damage stat already degrades; this proves the + // --- weapon also keeps firing (Firing stays true) at a partial grant, and only a true-zero grant stops it. --- + private (float damage, bool firing) RunConstantWeapon(float reactorCharge, float exponent = 1) + { + using var cache = OpenCatalog(new ConstantWeaponData + { + DamageType = DamageType.Kinetic, Damage = Curved(100, exponent), Penetration = Constant(0), + DamageSpread = Constant(0), MinRange = Constant(0), Range = Constant(0), Energy = Constant(50), + Heat = Constant(0), Visibility = Constant(0), MagazineSize = 0 + }); + var ship = BuildShip(cache, reactorCharge); + var weapon = ship.GetBehavior(); + weapon.Activate(); + ship.Update(1f); + return (weapon.Damage, weapon.Firing); + } + + [Fact] + public void ConstantWeaponAtHalfGrantKeepsFiringWithReducedDamage() + { + var (full, fullFiring) = RunConstantWeapon(reactorCharge: 1000); // demand 50, ratio 1 + var (half, halfFiring) = RunConstantWeapon(reactorCharge: 25); // demand 50, ratio .5 + + Assert.True(fullFiring); + Assert.True(halfFiring); // the flicking-off bug: this used to be false + Assert.True(half > 0f && half < full, $"half={half} should sit strictly between 0 and full={full}"); + } + + [Fact] + public void ConstantWeaponAtFullGrantIsUnchangedFromToday() + { + var (full, firing) = RunConstantWeapon(reactorCharge: 1000); + Assert.True(firing); + Assert.Equal(100f, full, 3); + } + + [Fact] + public void ConstantWeaponAtZeroGrantStopsFiringAndProducesNothing() + { + var (zero, firing) = RunConstantWeapon(reactorCharge: 0); + Assert.False(firing); + Assert.Equal(0f, zero, 3); + } + + [Fact] + public void ConstantWeaponDamageDegradesByItsAuthoredExponentNotLinearly() + { + var (half, firing) = RunConstantWeapon(reactorCharge: 25, exponent: 2); + Assert.True(firing); + Assert.Equal(25f, half, 3); // lerp(0, 100, pow(.5, 2)) == 25, not the linear-response 50 + } + + // --- EnergyDraw: named explicitly (docs/stats-and-power-target.md) as the one continuous consumer whose + // --- effect is not a performance stat at all -- its Execute return value IS the effect (Entity.cs's + // --- per-BehaviorGroup Execute chain reads it to decide whether later behaviours in the group run). There + // --- is nothing here for a curve to degrade continuously, so a partial grant still passes and only a true + // --- zero grant closes the gate. Execute is public and side-effect-free (a plain read of Item.PowerSupply), + // --- so it is safe to call directly for inspection after the same tick the group loop already ran it in. --- + private bool RunEnergyDraw(float reactorCharge) + { + using var cache = OpenCatalog(new EnergyDrawData { EnergyDraw = Constant(50), PerSecond = true }); + var ship = BuildShip(cache, reactorCharge); + ship.Update(1f); + return ship.GetBehavior().Execute(1f); + } + + [Fact] + public void EnergyDrawAtHalfGrantStillPasses() + { + Assert.True(RunEnergyDraw(reactorCharge: 25)); // demand 50, ratio .5 -- used to fail this gate entirely + } + + [Fact] + public void EnergyDrawAtFullGrantPasses() + { + Assert.True(RunEnergyDraw(reactorCharge: 1000)); + } + + [Fact] + public void EnergyDrawAtZeroGrantFails() + { + Assert.False(RunEnergyDraw(reactorCharge: 0)); + } + + // --- Regression: Cut 4's InputCapacitor all-or-nothing rule for instant items must survive Cut 7 completely + // --- untouched -- an input capacitor half full still refuses a whole-shot spend, because InstantWeapon, + // --- Sensor and Shield are unaffected by anything in this cut. Unit-level (no Ship/catalog needed at all): + // --- InputCapacitor is a plain class. --- + [Fact] + public void AnInputCapacitorStillRefusesToSpendOnAPartialCharge() + { + var capacitor = new InputCapacitor(); + capacitor.UpdateStats(energy: 10, cooldown: 1); // Capacity = 10, Rate = 10 + capacitor.AddCharge(5); // half charge -- real, but not a whole shot + + Assert.True(capacitor.CanSpend(5)); + Assert.False(capacitor.TrySpend(10)); // the whole-shot cost must still be refused outright + + capacitor.AddCharge(5); // now full + Assert.True(capacitor.TrySpend(10)); // and only now does it fire, for the whole cost + } +} diff --git a/tests/mutation_tests_stats_power_cut7.py b/tests/mutation_tests_stats_power_cut7.py new file mode 100644 index 000000000..e67cc5157 --- /dev/null +++ b/tests/mutation_tests_stats_power_cut7.py @@ -0,0 +1,204 @@ +#!/usr/bin/env python3 +"""Mutation tests for docs/stats-and-power-target.md's brownout ruling ("Continuous consumers brown out through +a power supply curve on their performance stats. An exponent is enough.") -- Cut 7 in this repo's own numbering, +following Cut 6 (mutation_tests_stats_power_cut6.py). + +Cut 6 wired a real curve into EquippedItem.PowerSupplyFactor and the bus already wrote a real fractional grant, +but every continuous consumer still gated its own effect on Item.PowerSupply >= 1f (Thruster.Execute, +AetherDrive.Execute, Radiator.Execute, ConstantWeapon.Execute, EnergyDraw.Execute) -- so a partial grant read +exactly like none, the flicking-off bug the ruling names. This cut removes each of those five gates (Radiator's +outright; the other four narrowed to a true-zero floor) and lets the already-curved performance stat (or, for +EnergyDraw, the plain pass/fail gate itself) carry the degradation instead. This script mutates each behaviour's +own changed line back toward the old all-or-nothing shape (or removes the newly-added epsilon floor) and asserts +the matching BrownoutTests.cs Fact goes red for exactly that reason. A no-op control mutation proves the +read/replace/restore path is transparent. + +Usage: + python tests/mutation_tests_stats_power_cut7.py --cultlib-root + +Only touches files under this repository; every mutation is reversed before the script exits, including on +failure. +""" +from __future__ import annotations + +import argparse +import subprocess +import sys +from dataclasses import dataclass +from pathlib import Path + +REPO_ROOT = Path(__file__).resolve().parent.parent +TEST_PROJECT = REPO_ROOT / "tests" / "Aetheria.Shared.Tests" + + +@dataclass +class Mutation: + rule: str + file: str + anchor: str + mutated: str + test: str + expect: str # "red" (mutant must be killed) or "green" (the no-op control) + + +MUTATIONS: list[Mutation] = [ + # --- No-op control: proves the anchor/replace/restore mechanism is transparent --- + Mutation( + rule="control (no-op round trip)", + file="Assets/Scripts/ServerShared/Behaviors/Thruster.cs", + anchor=" if(_input > .01f && Item.PowerSupply > 1e-4f)", + mutated=" if(_input > .01f && Item.PowerSupply > 1e-4f)", + test="BrownoutTests.ThrusterAtHalfGrantProducesReducedNotZeroNotFullThrust", + expect="green", + ), + + # --- Thruster: the gate must not demand a full grant any more. Reverting to the pre-cut ">= 1f" makes a + # --- half grant produce exactly nothing (the flicking-off bug), instead of a reduced, nonzero thrust. --- + Mutation( + rule="Thruster.Execute must not gate its effect on a full grant", + file="Assets/Scripts/ServerShared/Behaviors/Thruster.cs", + anchor=" if(_input > .01f && Item.PowerSupply > 1e-4f)", + mutated=" if(_input > .01f && Item.PowerSupply >= 1f)", + test="BrownoutTests.ThrusterAtHalfGrantProducesReducedNotZeroNotFullThrust", + expect="red", + ), + + # --- AetherDrive: the same rule, the same shape of mutation, on the rotor's own spin-up gate. --- + Mutation( + rule="AetherDrive.Execute must not gate its effect on a full grant", + file="Assets/Scripts/ServerShared/Behaviors/AetherDrive.cs", + anchor=" if (Item.PowerSupply > 1e-4f)", + mutated=" if (Item.PowerSupply >= 1f)", + test="BrownoutTests.AetherDriveAtHalfGrantProducesReducedNotZeroNotFullSpinUp", + expect="red", + ), + + # --- Radiator: Cut 7 deletes the gate outright rather than narrowing it (PumpedHeat's own curve already + # --- reduces the pump, and already zeroes it at true zero supply). Re-inserting the old gate line makes a + # --- half grant refuse to pump at all, same as a full shortfall. --- + Mutation( + rule="Radiator.Execute must not gate its pump on a full grant", + file="Assets/Scripts/ServerShared/Behaviors/Radiator.cs", + anchor=" var pumpedHeat = PumpedHeat * max(itemTemperature - _data.TemperatureFloor, 0);", + mutated=" if (Item != null && Item.PowerSupply < 1f) return false;\n\n var pumpedHeat = PumpedHeat * max(itemTemperature - _data.TemperatureFloor, 0);", + test="BrownoutTests.RadiatorAtHalfGrantPumpsReducedNotZeroNotFullHeat", + expect="red", + ), + + # --- ConstantWeapon: the exact bug the ruling names -- a partial grant used to safe the weapon off entirely + # --- (_firing = false), not merely fire it for less. Reverting to "< 1f" makes a half grant stop the weapon + # --- outright instead of merely firing it for reduced damage. --- + Mutation( + rule="ConstantWeapon.Execute must not safe the weapon off on anything less than a full grant", + file="Assets/Scripts/ServerShared/Behaviors/ConstantWeapon.cs", + anchor=" if (Item != null && Item.PowerSupply <= 1e-4f)", + mutated=" if (Item != null && Item.PowerSupply < 1f)", + test="BrownoutTests.ConstantWeaponAtHalfGrantKeepsFiringWithReducedDamage", + expect="red", + ), + + # --- EnergyDraw: the one continuous consumer with no performance stat of its own to curve -- its Execute + # --- return value IS its whole effect (Entity.cs's per-BehaviorGroup Execute chain). Reverting to ">= 1f" + # --- makes a half grant close the gate exactly like a full shortfall would. --- + Mutation( + rule="EnergyDraw.Execute must not demand a full grant to pass its gate", + file="Assets/Scripts/ServerShared/Behaviors/EnergyDraw.cs", + anchor=" return Item == null || Item.PowerSupply > 1e-4f;", + mutated=" return Item == null || Item.PowerSupply >= 1f;", + test="BrownoutTests.EnergyDrawAtHalfGrantStillPasses", + expect="red", + ), + + # --- The degradation must follow the authored exponent end-to-end through a newly-ungated consumer, not + # --- just in the abstract (mutation_tests_stats_power_cut6.py already pins this against a bare resolver + # --- read) -- dropping the exponent from PowerSupplyFactor collapses ConstantWeapon's own Damage curve to + # --- the identity-linear response regardless of what was authored. --- + Mutation( + rule="PowerSupplyFactor must raise PowerSupply to the term's own exponent for a real continuous consumer, not just a bare stat", + file="Assets/Scripts/ServerShared/Entity.cs", + anchor=" public float PowerSupplyFactor(float exponent) => pow(PowerSupply, exponent);", + mutated=" public float PowerSupplyFactor(float exponent) => PowerSupply;", + test="BrownoutTests.ConstantWeaponDamageDegradesByItsAuthoredExponentNotLinearly", + expect="red", + ), + + # --- Regression: Cut 4's InputCapacitor all-or-nothing rule for instant items must survive this cut + # --- completely untouched. Neutering the refusal check proves the regression test actually catches a + # --- violation, not merely that it happens to pass today. --- + Mutation( + rule="InputCapacitor.TrySpend must still refuse a cost it cannot cover", + file="Assets/Scripts/ServerShared/Behaviors/InputCapacitor.cs", + anchor=" if (!CanSpend(cost)) return false;", + mutated=" if (false) return false;", + test="BrownoutTests.AnInputCapacitorStillRefusesToSpendOnAPartialCharge", + expect="red", + ), +] + + +def replace_unique(path: Path, anchor: str, mutated: str) -> None: + original = path.read_text(encoding="utf-8") + count = original.count(anchor) + if count != 1: + raise SystemExit(f"{path}: anchor must occur exactly once, found {count}\n---\n{anchor}") + path.write_text(original.replace(anchor, mutated), encoding="utf-8") + + +def run_test(cultlib_root: str, test: str) -> tuple[int, str]: + proc = subprocess.run( + ["dotnet", "test", str(TEST_PROJECT), f"-p:CultLibRoot={cultlib_root}", + "--filter", f"FullyQualifiedName~{test}"], + capture_output=True, text=True, timeout=300, + ) + return proc.returncode, proc.stdout + proc.stderr + + +def main() -> int: + parser = argparse.ArgumentParser() + parser.add_argument("--cultlib-root", required=True) + args = parser.parse_args() + + failures: list[str] = [] + originals: dict[str, str] = {} + for m in MUTATIONS: + if m.file not in originals: + originals[m.file] = (REPO_ROOT / m.file).read_text(encoding="utf-8") + + def restore_all() -> None: + for file, text in originals.items(): + (REPO_ROOT / file).write_text(text, encoding="utf-8") + + try: + for m in MUTATIONS: + print(f"\n=== {m.rule} (expect {m.expect}) ===") + path = REPO_ROOT / m.file + replace_unique(path, m.anchor, m.mutated) + code, output = run_test(args.cultlib_root, m.test) + passed = "Passed!" in output and code == 0 + if m.expect == "green": + if not passed: + failures.append(f"{m.rule}: expected green (test passing), got failure\n{output[-2000:]}") + else: + print(f"OK: {m.test} passed under a no-op mutation, as expected") + else: + if passed: + failures.append(f"{m.rule}: expected red (mutant killed), but {m.test} still passed") + else: + print(f"OK: {m.test} went red under the mutation, as expected") + # Restore this file immediately so the next mutation starts from a clean tree. + path.write_text(originals[m.file], encoding="utf-8") + finally: + restore_all() + + if failures: + print("\n=== FAILURES ===") + for f in failures: + print(f"- {f}") + return 1 + + print("\nAll mutations behaved as declared.") + return 0 + + +if __name__ == "__main__": + sys.exit(main())