Six distinct fixes accumulated over live-test iterations against four bids (654473755566, 806245601092, 283192092460, 131549100204, 799755786270) — together they take the shadow engine from "throws on the first non-mulligan play" to "survives a full PvP battle, only weird-edge-case Unity touches still left to whack". 1. Engine StableRandom seed aligned with clients' Matched.seed (BattleSession.EnsureEngineSetup, NodeNativeBattleHarness.Create). Clients seed _stableRandom with BattleSeeds.Stable(masterSeed) (the value the node ships in Matched.seed); we were passing the RAW masterSeed to engine.Setup, so every StableRandom call diverged from call #1 onward — every turn-1+ draw picked a different deck position than the clients. Verified Stable(1184631275)=1543475792 matches the wire on bid 654473755566. 2. SeedDeck advances cardTotalNum to deck.Count+1 + pins BattleStartDeckCardList. Mirrors SBattleLoad.InitPlayer's tail (SBattleLoad.cs:1292). Without it, skill-generated tokens auto-assigned Index 0,1,... and COLLIDED with deck-loaded indices 1..40 — silent until something addressed the deck card with the colliding Index (Hoverboarder at deck idx 1 + a token at engine Index 1 made GetBattleCardIdx's SingleOrDefault throw on bid 806245601092). 3. BattleCardView.GameObject lazily non-null in the shim (ViewUiTouchStubs.cs). The IsRecovery card-create delegate (NetworkBattleManagerBase.cs:379) passes null cardGameObject; Skill_metamorphose.cs:147 in the in-play branch then NRE'd on `metamorphosedCard.BattleCardView.GameObject.transform.rotation = identity`, a purely cosmetic touch with no game-state implication. Bid 283192092460: Petrification on a board follower. 4. TranslateChoiceKeyAction unwraps wrapped selectCard on shadow ingest (SessionBattleEngine.cs, sibling to TranslateTargetOwners). Live sender-send wires Choice plays as selectCard:{cardId:[...], open:0}; engine's ConvertToListInt does `value as List<object>` — a Dict casts to null and foreach NREs. The receiver's swallow-all catch (NetworkBattleReceiver.cs:1255) logs to Debug.LogError + LocalLog — both shimmed/no-op'd headlessly — and returns false, but Receive calls ReceivedMessage with checkBreakData:false so the false isn't propagated. The play continues with choiceIdList=[], the chosen branch never resolves, the played card stays in hand; a later targeted play (A's bounce on B's "board" idx 20) then can't find the target → NRE on null in ActionProcessor.PlayCard:407. Bid 131549100204: B's Resonance + A's bounce. Opponent-relay path is unaffected — node strips selectCard from broadcasts. 5. HeadlessHandViewStub overrides HandUnfocus/HandFocus/FocusRearrangeHandHand to return NullVfx. CreateHandControl returns null in headless; the base methods unconditionally deref `_handControl.SetHandState(...)`. A follower with a when_spell_play Heal trigger fired on its leader for amount 0 — even a 0-heal drives ApplyHealing → CreatePullHandInVfx → HandUnfocus → NRE. Bid 799755786270: two consecutive spell plays both crashed this stack. Added InternalsVisibleTo("SVSim.BattleEngine.Tests") so the shim-level regression tests can pin the no-op contracts directly. Plus the previous-session fixes carried in this same uncommitted state (see docs/superpowers/plans/2026-06-07-shadow-engine-desync-handoff.md): - doesPlayerGoFirst:true + mgr.IsFirst:true (turn-1 draw count correct per seat) - RecoveryOperationCollection.PlayHandCardOperation routes all type:30 through PlaySkillSelectHandCardOperation (skips the two-phase user-select guard that aborts targeted spells in recovery) - ShadowFeed + ToRawBody: server-generated typed bodies (DealBody, etc.) converted to RawBody before engine.Receive (`env.Body as RawBody` returned null for typed bodies) - Ready idxChangeSeed seeds A's XorShift via the receiver; B's seed is injected via SeedOppoIdxChange (BattleSeeds.IdxChange + viewerId) - ReadySpin defaulted to 0 (was 243) — non-zero double-cranks the shadow which ingests BOTH sides' Ready frames on one stream Test counts: SVSim.UnitTests 1054/1054, SVSim.BattleEngine.Tests 34/34. Open: known-residual Unity touches are individual whack-a-mole now (per-card skill edge cases), not the structural divergences fixed here. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
183 lines
11 KiB
C#
183 lines
11 KiB
C#
using System.Collections.Generic;
|
|
using System.Linq;
|
|
using System.Text.Json.Nodes;
|
|
using NUnit.Framework;
|
|
using SVSim.BattleNode.Protocol;
|
|
using SVSim.BattleNode.Sessions.Engine;
|
|
|
|
namespace SVSim.BattleEngine.Tests.SessionEngine
|
|
{
|
|
/// <summary>
|
|
/// PHASE 4 STEP 1 — Tier 2 capture-replay root-cause VERIFICATION (NOT a fix).
|
|
///
|
|
/// Replays the FRESH smoke captures (battle 907324319325) — battle_test_fresh_cl1/cl2.ndjson —
|
|
/// through a <see cref="SessionBattleEngine"/>, then measures whether the per-seat <c>idxChangeSeed</c>
|
|
/// the real Ready frame carries is what controls the "Target card was not found in hand cards"
|
|
/// divergence symptom.
|
|
///
|
|
/// FAITHFUL SETUP (the live ShadowIngest only feeds client SENDS, which contain NO Deal/Ready, so a
|
|
/// bare send-only replay can't even seat a hand — that conflates "missing Deal" with "missing
|
|
/// reshuffle"). To ISOLATE the reshuffle/seed effect we seat each seat's hand from its OWN client's
|
|
/// RECEIVE Deal + Swap + Ready (the frames that establish the hand and reach mulligan-end), then replay
|
|
/// both clients' interleaved SENDS (the plays). The Ready frame natively carries the real per-seat
|
|
/// idxChangeSeed (cl1=1430655717, cl2=661650374), and the engine's recovery receiver calls
|
|
/// <c>CreateXorShift</c> from it (NetworkBattleReceiver.cs:1125-1126). The A/B is then:
|
|
/// • WITH-SEED: ingest the Ready frame verbatim (idxChangeSeed present) -> XorShift active;
|
|
/// • SEED-STRIPPED: ingest the SAME Ready frame with idxChangeSeed forced to -1 -> XorShift inactive
|
|
/// (this is exactly the live shadow's effective state, since it never ingests the seed-bearing Ready).
|
|
/// The ONLY difference between the two runs is whether the seed reaches CreateXorShift.
|
|
///
|
|
/// DECK SETUP MECHANISM (feasibility crux, RESOLVED): each side's deck is reconstructed from the
|
|
/// capture's <c>Matched.selfDeck</c> (idx->cardId, the exact shuffled order the node also handed the
|
|
/// client) via <see cref="CaptureReplay.SelfDeckFrom"/>; the master seed from <c>Matched.selfInfo.seed</c>.
|
|
/// The deck IS in the socket capture — no external fixture needed.
|
|
/// </summary>
|
|
[TestFixture]
|
|
[NonParallelizable]
|
|
public class CaptureReplayReshuffleRootCauseTests
|
|
{
|
|
private static readonly HashSet<string> SkipUris = new()
|
|
{
|
|
nameof(NetworkBattleUri.Echo),
|
|
nameof(NetworkBattleUri.ChatStamp),
|
|
nameof(NetworkBattleUri.Gungnir),
|
|
};
|
|
|
|
private static readonly HashSet<string> MulliganUris = new()
|
|
{
|
|
nameof(NetworkBattleUri.Deal),
|
|
nameof(NetworkBattleUri.Swap),
|
|
nameof(NetworkBattleUri.Ready),
|
|
};
|
|
|
|
private sealed record ReplayOutcome(
|
|
int FrameCount, List<string> Divergences, bool AllDivergencesPostMulligan, bool SelfXorShiftActive);
|
|
|
|
// Re-parse a captured frame, overriding the Ready body's idxChangeSeed (and oppoIdxChangeSeed if
|
|
// present). Used to STRIP the seed (-1) to model the live shadow's seed-less state.
|
|
private static MsgEnvelope OverrideReadySeed(CapturedFrame f, int newSeed)
|
|
{
|
|
var obj = JsonNode.Parse(f.RawBody)!.AsObject();
|
|
obj["idxChangeSeed"] = newSeed;
|
|
if (obj.ContainsKey("oppoIdxChangeSeed")) obj["oppoIdxChangeSeed"] = newSeed;
|
|
return MsgEnvelope.FromJson(obj.ToJsonString());
|
|
}
|
|
|
|
/// <summary>Seat both hands from each client's receive Deal+Swap+Ready, then replay both clients'
|
|
/// interleaved SENDS. <paramref name="stripSeed"/> forces the Ready idxChangeSeed to -1 (the live
|
|
/// shadow's effective state). Returns divergences + the post-setup self XorShift state.</summary>
|
|
private static ReplayOutcome Replay(bool stripSeed)
|
|
{
|
|
var cl1 = CaptureReplay.Load("battle_test_fresh_cl1.ndjson");
|
|
var cl2 = CaptureReplay.Load("battle_test_fresh_cl2.ndjson");
|
|
|
|
var deckA = CaptureReplay.SelfDeckFrom(cl1);
|
|
var deckB = CaptureReplay.SelfDeckFrom(cl2);
|
|
Assert.That(deckA, Is.Not.Empty, "cl1 Matched.selfDeck must reconstruct seat A's deck");
|
|
Assert.That(deckB, Is.Not.Empty, "cl2 Matched.selfDeck must reconstruct seat B's deck");
|
|
|
|
var engine = new SessionBattleEngine();
|
|
engine.Setup(masterSeed: CaptureReplay.SeedFrom(cl1), seatADeck: deckA, seatBDeck: deckB);
|
|
Assert.That(engine.IsReady, Is.True, "engine must seat from the captured decks + seed");
|
|
|
|
var divergences = new List<string>();
|
|
bool sawMulliganEnd = false;
|
|
bool anyDivergencePreMulligan = false;
|
|
|
|
void Ingest(MsgEnvelope env, bool seat, string uri)
|
|
{
|
|
if (MulliganUris.Contains(uri)) sawMulliganEnd = true;
|
|
var r = engine.Receive(env, isPlayerSeat: seat);
|
|
if (r.Diverged)
|
|
{
|
|
divergences.Add($"seat={(seat ? "A" : "B")} {uri}: {Trim(r.RejectReason)}");
|
|
if (!sawMulliganEnd) anyDivergencePreMulligan = true;
|
|
}
|
|
}
|
|
|
|
// --- Phase 1: seat both hands from the receive setup frames ----------------------------------
|
|
// A single Deal seats BOTH opening hands (cl1's receive Deal carries self=A + oppo=B), so we
|
|
// ingest Deal ONCE (as seat A) — ingesting both clients' Deals would double-deal (NRE / "Sequence
|
|
// contains more than one"). Each seat's Swap then applies that seat's mulligan, and each seat's
|
|
// Ready carries THAT seat's idxChangeSeed (cl1's for A, cl2's for B; the recovery receiver consumes
|
|
// only the SELF seed per ingest, NetworkBattleReceiver.cs:1126), reaching mulligan-end per seat.
|
|
CapturedFrame Receive(IReadOnlyList<CapturedFrame> frames, string uri) =>
|
|
frames.First(f => f.Direction == "receive" && f.Uri == uri);
|
|
|
|
// Deal once (seat A's receive Deal seats both hands).
|
|
Ingest(Receive(cl1, nameof(NetworkBattleUri.Deal)).Env, seat: true, nameof(NetworkBattleUri.Deal));
|
|
// Each seat's mulligan swap, then each seat's Ready (its own seed).
|
|
foreach (var (frames, seat) in new[] { (cl1, true), (cl2, false) })
|
|
{
|
|
Ingest(Receive(frames, nameof(NetworkBattleUri.Swap)).Env, seat, nameof(NetworkBattleUri.Swap));
|
|
var ready = Receive(frames, nameof(NetworkBattleUri.Ready));
|
|
var readyEnv = stripSeed ? OverrideReadySeed(ready, -1) : ready.Env;
|
|
Ingest(readyEnv, seat, nameof(NetworkBattleUri.Ready));
|
|
}
|
|
|
|
bool selfActive = engine.SelfXorShiftActive;
|
|
|
|
// --- Phase 2: replay both clients' interleaved SENDS (the plays / turn ops) -------------------
|
|
var sends = CaptureReplay.InterleavedSends(cl1, cl2)
|
|
.Where(x => !SkipUris.Contains(x.Env.Uri.ToString()))
|
|
.ToList();
|
|
foreach (var (env, seat) in sends)
|
|
Ingest(env, seat, env.Uri.ToString());
|
|
|
|
return new ReplayOutcome(
|
|
FrameCount: sends.Count, divergences, !anyDivergencePreMulligan, selfActive);
|
|
}
|
|
|
|
private static string Trim(string? s) =>
|
|
(s ?? "").Split(" @ ")[0];
|
|
|
|
[Test]
|
|
public void Capture_replay_reproduces_post_mulligan_divergence_and_pins_what_the_seed_does_not_fix()
|
|
{
|
|
var withSeed = Replay(stripSeed: false);
|
|
var stripped = Replay(stripSeed: true);
|
|
|
|
TestContext.WriteLine($"WITH-SEED (Ready idxChangeSeed present): selfXorShiftActive={withSeed.SelfXorShiftActive} " +
|
|
$"playFrames={withSeed.FrameCount} divergences={withSeed.Divergences.Count}");
|
|
foreach (var d in withSeed.Divergences) TestContext.WriteLine(" DIVERGE " + d);
|
|
TestContext.WriteLine($"SEED-STRIPPED (idxChangeSeed=-1, the live shadow state): selfXorShiftActive={stripped.SelfXorShiftActive} " +
|
|
$"playFrames={stripped.FrameCount} divergences={stripped.Divergences.Count}");
|
|
foreach (var d in stripped.Divergences) TestContext.WriteLine(" DIVERGE " + d);
|
|
|
|
Assert.Multiple(() =>
|
|
{
|
|
// (1) The reported symptom reproduces DETERMINISTICALLY from the captures: the replay diverges,
|
|
// including the verbatim "Target card was not found in hand cards" exception.
|
|
Assert.That(withSeed.Divergences, Is.Not.Empty,
|
|
"the capture replay must reproduce the divergence symptom");
|
|
Assert.That(withSeed.Divergences.Any(d => d.Contains("not found in hand")), Is.True,
|
|
"the reported 'Target card was not found in hand cards' symptom must reproduce");
|
|
|
|
// (2) All divergences occur AFTER the mulligan barrier — consistent with a post-mulligan cause.
|
|
Assert.That(withSeed.AllDivergencesPostMulligan, Is.True, "with-seed divergences are post-mulligan");
|
|
Assert.That(stripped.AllDivergencesPostMulligan, Is.True, "stripped divergences are post-mulligan");
|
|
|
|
// (3) The wire seed DOES drive the engine's XorShift gate (NetworkBattleReceiver.cs:1126):
|
|
// present -> active, stripped (the live shadow's state) -> inactive.
|
|
Assert.That(withSeed.SelfXorShiftActive, Is.True,
|
|
"ingesting the real Ready (idxChangeSeed present) activates the engine's XorShift");
|
|
Assert.That(stripped.SelfXorShiftActive, Is.False,
|
|
"stripping idxChangeSeed (the live shadow's state) leaves the XorShift inactive");
|
|
|
|
// (4) THE KEY VERIFICATION FINDING — activating the XorShift via the wire seed does NOT, on its
|
|
// own, change the divergence count. The engine's recovery/watch RECEIVE path never performs
|
|
// the post-mulligan full-deck reshuffle the live client does: the XorShift's GetChangeInt is
|
|
// consumed ONLY by AddToDeckCardIndexChange (BattlePlayerBase.cs:3079) for cards added to the
|
|
// deck AFTER mulligan-end, and the per-turn draw is engine-computed off the (un-reshuffled)
|
|
// deck order, not driven by the wire's `move idx`. So "feed the seed" alone does NOT fix the
|
|
// desync headless — the eventual fix must also make the engine reshuffle the deck post-
|
|
// mulligan to match the client (or drive the draw from the wire idx). We PIN this here.
|
|
Assert.That(stripped.Divergences.Count, Is.EqualTo(withSeed.Divergences.Count),
|
|
"VERIFIED: activating the XorShift via the wire seed alone does NOT change the divergence " +
|
|
"count — the engine's receive path does not reshuffle the deck, so the seed is necessary " +
|
|
"but NOT sufficient (the fix needs the reshuffle too, not just the seed)");
|
|
});
|
|
}
|
|
}
|
|
}
|