test(battlenode): N1 shadow replay tracks captured battle state (Phase 2 N1)

Full single-client capture replay (cl1 send=player seat, receive=opponent seat,
ts-ordered) ingests end-to-end: 33 frames, 0 rejects, 0 invariant violations at
turn boundaries (leader life/PP/board/hand).

Headless gaps filled per playbook (no Engine/ drift):
- IsRecovery=true after construction: the engine's own headless replay mode gates
  the live view/UI layer off (BattleUIContainer, turn-control UI, VFX waits) while
  keeping the live NetworkBattleReceiver (ND4) and authoritative state.
- Seed ToolboxGame.RealTimeNetworkAgent, BattleUIContainer, _backGround, and
  per-player NullPlayerEmotion no-ops the receive/turn cycle dereferences.
- _IfaceImpl.g.cs (shim, not Engine/): BattleCardView.BattleCardIconAnimations
  returns a lazy non-null no-op so the opponent card-reveal icon-init (deferred
  VFX) doesn't NRE.
- HeadlessCardMaster.Load made cumulative: it replaced the global CardMaster each
  call, so a Load(deck) evicted the oracle card set and broke tests run after.

Adds board-state accessors (LeaderLife/Pp/HandCount/BoardCount) and CaptureReplay
ts ordering.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
This commit is contained in:
gamer147
2026-06-06 15:28:08 -04:00
parent 6740313446
commit fa86739ac2
5 changed files with 195 additions and 6 deletions

View File

@@ -19,10 +19,18 @@ namespace SVSim.BattleEngine.Tests
private static readonly string CardsJsonPath =
Path.Combine(AppContext.BaseDirectory, "Data", "cards.json");
// Load the given card ids (empty = none) into a fresh CardMaster registered as Default.
// Every id ever requested this process. Load is CUMULATIVE: each call rebuilds the master from
// the union, so a later Load(subset) never evicts cards an earlier Load (e.g. EnsureInitialized's
// oracle set) installed. Without this, the static CardMaster is shared mutable state across the
// whole NUnit run and a Load(deck) in one test silently breaks an oracle test that runs after.
private static readonly HashSet<int> _everLoaded = new();
// Load the given card ids (empty = none) into a CardMaster registered as Default, MERGED with all
// previously-loaded ids.
public static void Load(params int[] cardIds)
{
var want = new HashSet<int>(cardIds);
foreach (var id in cardIds) _everLoaded.Add(id);
var want = new HashSet<int>(_everLoaded);
var rows = new List<CardCSVData>();
if (want.Count > 0)
{

View File

@@ -1,5 +1,6 @@
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Text.Json;
@@ -8,7 +9,7 @@ using SVSim.BattleNode.Protocol;
namespace SVSim.BattleEngine.Tests.SessionEngine
{
internal sealed record CapturedFrame(string Direction, string Uri, MsgEnvelope Env, string RawBody);
internal sealed record CapturedFrame(DateTime Ts, string Direction, string Uri, MsgEnvelope Env, string RawBody);
/// <summary>Parses a battle_test ndjson capture into MsgEnvelopes the engine can ingest.
///
@@ -29,6 +30,9 @@ namespace SVSim.BattleEngine.Tests.SessionEngine
using var doc = JsonDocument.Parse(line);
var root = doc.RootElement;
var direction = root.TryGetProperty("direction", out var dEl) ? dEl.GetString() ?? "" : "";
var ts = root.TryGetProperty("ts", out var tsEl) && tsEl.ValueKind == JsonValueKind.String
? DateTime.Parse(tsEl.GetString()!, CultureInfo.InvariantCulture, DateTimeStyles.RoundtripKind)
: default;
if (!root.TryGetProperty("body", out var bodyEl) || bodyEl.ValueKind != JsonValueKind.Object)
continue;
@@ -50,7 +54,7 @@ namespace SVSim.BattleEngine.Tests.SessionEngine
MsgEnvelope env;
try { env = MsgEnvelope.FromJson(normalized); }
catch { continue; } // out-of-model / unparseable line
frames.Add(new CapturedFrame(direction, uri, env, normalized));
frames.Add(new CapturedFrame(ts, direction, uri, env, normalized));
}
return frames;
}

View File

@@ -0,0 +1,82 @@
using System.Collections.Generic;
using System.Linq;
using NUnit.Framework;
using SVSim.BattleNode.Protocol;
using SVSim.BattleNode.Sessions.Engine;
namespace SVSim.BattleEngine.Tests.SessionEngine
{
[TestFixture]
public class SessionEngineShadowReplayTests
{
// Frames that are transport/keepalive, not game actions — not ingested.
private static readonly HashSet<string> SkipUris = new()
{
nameof(NetworkBattleUri.Echo),
nameof(NetworkBattleUri.ChatStamp),
nameof(NetworkBattleUri.Gungnir),
};
[Test]
public void Shadow_replay_of_captured_battle_tracks_state_without_desync()
{
HeadlessEngineEnv.EnsureInitialized();
var cl1 = CaptureReplay.Load("battle_test_cl1.ndjson");
var cl2 = CaptureReplay.Load("battle_test_cl2.ndjson");
var deckA = CaptureReplay.SelfDeckFrom(cl1);
var deckB = CaptureReplay.SelfDeckFrom(cl2);
// One Load call with every id — Load replaces the static master each call.
HeadlessCardMaster.Load(deckA.Concat(deckB).Select(x => (int)x).Distinct().ToArray());
var engine = new SessionBattleEngine();
engine.Setup(masterSeed: CaptureReplay.SeedFrom(cl1), seatADeck: deckA, seatBDeck: deckB);
// Single-client full-stream replay (cl1 as the player seat): cl1's SENT frames are its own
// actions (seat=true); its RECEIVED frames are the opponent/server actions (seat=false),
// incl. the Deal that establishes both hands. This is exactly the stream cl1's receiver
// processed, in capture (ts) order. (The node-side both-clients-sends model is exercised
// live in Task 7; here we validate engine tracking against ground truth.)
var stream = cl1.Where(f => !SkipUris.Contains(f.Uri))
.OrderBy(f => f.Ts)
.ToList();
var rejects = new List<string>();
var violations = new List<string>();
foreach (var f in stream)
{
bool seat = f.Direction == "send";
var r = engine.Receive(f.Env, isPlayerSeat: seat);
if (r.RejectReason is not null)
rejects.Add($"{f.Direction} {f.Uri}: {r.RejectReason}");
if (f.Uri == nameof(NetworkBattleUri.TurnEnd))
CheckInvariants(engine, violations, atUri: f.Uri);
}
foreach (var line in rejects) TestContext.WriteLine("REJECT " + line);
foreach (var line in violations) TestContext.WriteLine("VIOLATION " + line);
TestContext.WriteLine($"frames={stream.Count} rejects={rejects.Count} violations={violations.Count}");
Assert.Multiple(() =>
{
Assert.That(rejects, Is.Empty, "engine diverged / rejected a captured frame");
Assert.That(violations, Is.Empty, "engine state left a structural invariant");
});
}
private static void CheckInvariants(SessionBattleEngine engine, List<string> violations, string atUri)
{
foreach (var seat in new[] { true, false })
{
int life = engine.LeaderLife(seat), pp = engine.Pp(seat);
int board = engine.BoardCount(seat), hand = engine.HandCount(seat);
if (life is < 0 or > 20) violations.Add($"{atUri} seat={seat} life={life}");
if (pp is < 0 or > 10) violations.Add($"{atUri} seat={seat} pp={pp}");
if (board is < 0 or > 7) violations.Add($"{atUri} seat={seat} board={board}");
if (hand is < 0 or > 9) violations.Add($"{atUri} seat={seat} hand={hand}");
}
}
}
}