Files
SVSimServer/SVSim.BattleEngine.Tests/RngSeamTests.cs
gamer147 2d9a6eea4b engine cleanup passes 4-7 + multi-instancing ambient rip
Squashes 146 commits from battle-engine-extraction. Net: 2,045 files changed,
+11,896 / -158,687 lines. Ships engine passes 4-7 (dead-code cull, view-layer
stub, receive-path shrink) plus the Phase-5 AsyncLocal ambient deletion that
turns concurrent battles into a type-system property rather than a scope
contract.

## What landed

**Passes 4-7 (chunks 1-34):** Extended the Phase-4 const-false collapse into a
cascading cull across the skill graph, view layer, and receive-path periphery.
Six mode flags (IsWatchBattle/IsReplayBattle/IsAdmin/IsAdminWatch/IsPuzzleQuest/
IsAINetwork) became `const false`, every guarded block deleted. Field*.cs
subclass ctors + BackGroundBase + ObjectChecker culled to no-ops. Mulligan
family reworked to take a mgr param through IMulliganMgr.InitMulligan.
Emotion/Recovery/Resource clusters null-stubbed. Prediction/OperationSimulator/
skill filters converted from static ambient reads to per-mgr reads via
SkillPrm.ownerCard.SelfBattlePlayer.BattleMgr / ins.BattleMgr / this.BattleMgr.

**Phase-5 ambient rip (chunks 35-47):** Deleted BattleAmbient / BattleAmbient-
Context / TestBattleScope in full. Every per-battle mutable slot now lives on
the mgr instance itself:
  mgr.InstanceIsForecast / InstanceIsRandomDraw / InstanceRecoveryInfo /
  InstanceViewerId / InstanceNetworkAgent / GameMgr
BattleManagerBase.GetIns() returns null unconditionally; the residual static
flags + 3 façades (Certification.ViewerId, Data.BattleRecoveryInfo,
ToolboxGame.RealTimeNetworkAgent) are null-tolerant defaults kept for the
handful of engine-internal readers that still reference their types. Zero
BattleAmbient references anywhere in engine + node + tests.

Added pre-seeded GameMgr ctor overload threaded through the mgr chain
(BattleManagerBase → SingleBattleMgr / NetworkBattleManagerBase → NetworkStandard-
BattleMgr → HeadlessBattleMgr / HeadlessNetworkBattleMgr). Fixtures build a
GameMgr, seed it via HeadlessEngineEnv.SeedCharaIds/SeedNetUser, and pass it
to the mgr's ctor — no ambient reach.

Node side (SVSim.BattleNode/SessionBattleEngine): _ctx replaced with a plain
GameMgr field; 34 `using var _ambient = BattleAmbient.Enter(_ctx)` scope wraps
ripped from every accessor and mutator; EngineGlobalInit.WirePerSessionGameMgr
takes GameMgr as a param and runs from SessionBattleEngine.SetupInternal
BEFORE mgr construction.

Test side: TestBattleScope deleted; 18 fixture [SetUp]s migrated to
`HeadlessEngineEnv.EnsureProcessGlobals()`; MultiInstanceEngineTests rewritten
around per-mgr construction (GetIns() → null is the pinned invariant).

## Regression fixes

- **chunk-48** (MulliganCtrl): chunk-35's `= null` stubs on card lookups broke
  the live receive-driven Deal path (BattlePlayerBase.DrawCard NRE'd downstream
  of NetworkPlayerMulliganCtrl.StartMulliganVfx). Restored the three lookups
  via `_battlePlayer.BattleMgr.GetBattleCardIdx`. Engine tests were satisfied
  by the WireMulliganPhase seam; unit tests exposed the live-path gap.

## Ship state

- SVSim.BattleEngine.Tests: 56/56 pass, 2 skip
- SVSim.UnitTests: 1554/1554 pass (was 1523/31-fail before chunk 48)
- Solution build: 0 source warnings (40 pre-existing NU1902 MessagePack CVEs
  in SVSim.EmulatedEntrypoint, unrelated)
- Sequential PVP smoke: verified live (two back-to-back battles, no regression
  on cleanup/spinup)
- Concurrent PVP smoke: verified live

Adds tools/engine-port/ClosureAnalyzer/ — the Roslyn transitive-type-closure
analyzer needed to make future cascade cleanup safe (per feedback memory
"Engine cleanup needs closure tool" from the 2026-06-28 pass-3 failure).

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-07-03 19:18:54 -04:00

102 lines
5.2 KiB
C#

using System;
using NUnit.Framework;
using SVSim.BattleEngine.Rng;
using Wizard;
using Wizard.Battle;
namespace SVSim.BattleEngine.Tests
{
[TestFixture]
public class RngSeamTests
{
[SetUp] public void SetUp() => HeadlessEngineEnv.EnsureProcessGlobals();
// RandomSourceBridge.Range must mirror the engine's exact roll arithmetic:
// BattleManagerBase.StableRandom does `(int)Math.Floor((double)val * unit)`.
[Test]
public void Bridge_Range_mirrors_engine_floor_arithmetic()
{
Assert.That(RandomSourceBridge.Range(7, 0.0), Is.EqualTo(0)); // floor(7*0) = 0
Assert.That(RandomSourceBridge.Range(7, 0.999), Is.EqualTo(6)); // floor(6.993) = 6 (never == val)
Assert.That(RandomSourceBridge.Range(3, 0.5), Is.EqualTo(1)); // floor(1.5) = 1 (middle of 3)
Assert.That(RandomSourceBridge.Range(1, 0.5), Is.EqualTo(0)); // floor(0.5) = 0
}
// SeededRandomSource(seed) must reproduce the engine's own generators EXACTLY: BattleManagerBase
// seeds both _stableRandom and _stableRandomOnlySelf as `new System.Random(RandomSeed)`
// (BattleManagerBase.cs:721-722). NextUnit() == synced.NextDouble(); NextSelf(max) == self.Next(max).
[Test]
public void SeededSource_reproduces_two_System_Random_streams()
{
const int seed = 12345;
var src = new SeededRandomSource(seed);
var refSynced = new System.Random(seed); // mirrors _stableRandom
var refSelf = new System.Random(seed); // mirrors _stableRandomOnlySelf (separate stream)
for (int i = 0; i < 8; i++)
Assert.That(src.NextUnit(), Is.EqualTo(refSynced.NextDouble()), $"NextUnit drift at {i}");
for (int i = 0; i < 8; i++)
Assert.That(src.NextSelf(100), Is.EqualTo(refSelf.Next(100)), $"NextSelf drift at {i}");
}
// ScriptedRandomSource feeds a known sequence (the oracle's control + the Phase-3 replay seam).
// It MUST throw on overrun, not wrap: an unexpected extra roll should fail loudly so a test
// surfaces a miscount of engine RNG calls rather than silently reusing a value.
[Test]
public void ScriptedSource_returns_sequence_then_throws_on_overrun()
{
var src = new ScriptedRandomSource(new[] { 0.1, 0.5 }, new[] { 3 });
Assert.That(src.NextUnit(), Is.EqualTo(0.1));
Assert.That(src.NextUnit(), Is.EqualTo(0.5));
Assert.That(() => src.NextUnit(), Throws.InvalidOperationException, "should throw on unit overrun");
Assert.That(src.NextSelf(99), Is.EqualTo(3));
Assert.That(() => src.NextSelf(99), Throws.InvalidOperationException, "should throw on self overrun");
}
// The decoupling (F2): the override must roll REAL values even though IsForecast == true (which
// forces the un-overridden engine methods to return 0). A ScriptedRandomSource proves the value
// came from the injected source, not the engine's zeroing.
[Test]
public void Override_rolls_real_values_under_IsForecast()
{
BattleManagerBase.IsForecast = true; // would zero the un-overridden engine RNG
// 3 units; with RandomSourceBridge.Range(val, unit) = floor(val*unit):
// StableRandom(7) with 0.5 -> floor(3.5) = 3
// StableRandomDouble() -> 0.25
// StableRandomOnlySelf(10) -> scripted self pick 4
var src = new ScriptedRandomSource(new[] { 0.5, 0.25 }, new[] { 4 });
var mgr = HeadlessEngineEnv.NewSeededHeadlessBattleMgr(src);
Assert.That(mgr.StableRandom(7), Is.EqualTo(3), "StableRandom did not use the injected source");
Assert.That(mgr.randomResult, Is.EqualTo(0.5), "StableRandom must set randomResult to the rolled unit");
Assert.That(mgr.StableRandomDouble(), Is.EqualTo(0.25), "StableRandomDouble did not use the injected source");
Assert.That(mgr.randomResult, Is.EqualTo(0.25), "StableRandomDouble must set randomResult");
Assert.That(mgr.StableRandomOnlySelf(10), Is.EqualTo(4), "StableRandomOnlySelf did not use the injected source");
}
// Parity: with the DEFAULT (seeded) source, HeadlessBattleMgr.StableRandom must equal what the
// verbatim engine would compute — floor(val * new System.Random(seed).NextDouble()) — pinning the
// re-authored RandomSourceBridge arithmetic to the engine's own formula+generator. (The default
// source seeds from HeadlessContentsCreator.RandomSeed == 12345.)
[Test]
public void Default_source_matches_engine_generator_and_formula()
{
BattleManagerBase.IsForecast = true;
var mgr = HeadlessEngineEnv.NewSeededHeadlessBattleMgr(); // default SeededRandomSource(12345)
var reference = new System.Random(12345);
for (int i = 0; i < 10; i++)
{
int expected = (int)System.Math.Floor(7 * reference.NextDouble());
Assert.That(mgr.StableRandom(7), Is.EqualTo(expected), $"parity drift at roll {i}");
}
}
}
}