fix(battlenode): shadow engine tracks live PvP wire-truth (full battle, multiple bid regressions)
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>
This commit is contained in:
@@ -1,5 +1,7 @@
|
||||
using System.Net.WebSockets;
|
||||
using System.Text.Json;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using SVSim.BattleNode.Lifecycle;
|
||||
using SVSim.BattleNode.Protocol;
|
||||
using SVSim.BattleNode.Sessions.Dispatch;
|
||||
using SVSim.BattleNode.Sessions.Dispatch.Handlers;
|
||||
@@ -35,6 +37,21 @@ public sealed class BattleSession
|
||||
/// never retried, never fatal.</summary>
|
||||
private bool _engineSetupAttempted;
|
||||
|
||||
/// <summary>Guards: server-generated Deal is fed to the shadow engine exactly once (the first
|
||||
/// occurrence from either LoadedHandler invocation). Deal + Ready are server-generated frames the
|
||||
/// engine needs to drive the mulligan: Deal → StartDeal (cards deck→hand for the player seat,
|
||||
/// _firstDrawList for the opponent), Ready → CompleteMulligan → EnemyChangeCardVfx → opponent
|
||||
/// DrawFirstMulliganCard. Without them the engine's hand stays empty and every play throws
|
||||
/// "Target card was not found in hand cards".</summary>
|
||||
private bool _engineDealFed;
|
||||
|
||||
/// <summary>Guards: server-generated Ready is fed to the shadow engine exactly once (the first
|
||||
/// Ready addressed to participant A). Fed as isPlayerSeat=false so the recovery path's
|
||||
/// OperateMulligan enters the OperateOppoMulligan branch — the only branch that invokes
|
||||
/// ReceiveOpponentMulligan → EnemyChangeCardVfx → DrawFirstMulliganCard. The player's mulligan
|
||||
/// was already processed during the Swap feed.</summary>
|
||||
private bool _engineReadyFed;
|
||||
|
||||
/// <summary>True once this session has acquired the process-wide <see cref="Engine.EngineSessionGate"/>
|
||||
/// (and is therefore the single active engine owner). Drives the matching <c>Release</c> at battle
|
||||
/// end so the next session can take the engine.</summary>
|
||||
@@ -241,13 +258,89 @@ public sealed class BattleSession
|
||||
}
|
||||
|
||||
if (Handlers.TryGetValue(env.Uri, out var handler))
|
||||
return handler.Handle(BuildContext(from, env));
|
||||
{
|
||||
var routes = handler.Handle(BuildContext(from, env));
|
||||
try { ShadowFeedServerFrames(routes); }
|
||||
catch (Exception ex)
|
||||
{
|
||||
_log.LogWarning(ex, "BattleSession {Bid}: shadow engine error feeding server frames (ignored)", BattleId);
|
||||
}
|
||||
return routes;
|
||||
}
|
||||
|
||||
_log.LogDebug("BattleSession {Bid}: dropping uri={Uri} in lifecycle={Lifecycle} from vid={Vid}",
|
||||
BattleId, env.Uri, Lifecycle, from.ViewerId);
|
||||
return Array.Empty<DispatchRoute>();
|
||||
}
|
||||
|
||||
/// <summary>Feed server-generated mulligan frames (Deal, Swap response, Ready) into the shadow
|
||||
/// engine. These frames are produced by LoadedHandler/SwapHandler and dispatched only to clients
|
||||
/// — they never enter <see cref="ShadowIngest"/> because they're not client-sent. But the engine
|
||||
/// needs them to drive the mulligan: Deal seats the hand, Ready completes the opponent's hand.
|
||||
/// The test harness (<c>NodeNativeBattleHarness</c>) feeds these directly; this method is the
|
||||
/// live-session equivalent.</summary>
|
||||
private void ShadowFeedServerFrames(IReadOnlyList<DispatchRoute> routes)
|
||||
{
|
||||
if (!_engine.IsReady) return;
|
||||
|
||||
foreach (var (target, frame, _) in routes)
|
||||
{
|
||||
switch (frame.Uri)
|
||||
{
|
||||
case NetworkBattleUri.Deal when !_engineDealFed:
|
||||
_engineDealFed = true;
|
||||
_log.LogWarning("BattleSession {Bid}: DEAL DIAG BEFORE: {Diag}",
|
||||
BattleId, _engine.DiagnoseDealState());
|
||||
ShadowFeed(frame, isPlayerSeat: true, "Deal");
|
||||
_log.LogWarning("BattleSession {Bid}: DEAL DIAG AFTER: {Diag}",
|
||||
BattleId, _engine.DiagnoseDealState());
|
||||
break;
|
||||
|
||||
case NetworkBattleUri.Swap:
|
||||
// The Swap RESPONSE (server-authored, carries post-mulligan self hand as
|
||||
// pos→idx) must go to the engine for the correct seat. The client-sent Swap
|
||||
// ({idxList}) also enters ShadowIngest but is harmless — its selfIdxList
|
||||
// parses to null (no "self" key) so FirstMulliganOperation no-ops.
|
||||
bool swapIsPlayer = ReferenceEquals(target, A);
|
||||
ShadowFeed(frame, swapIsPlayer, $"SwapResponse({(swapIsPlayer ? "A" : "B")})");
|
||||
break;
|
||||
|
||||
case NetworkBattleUri.Ready when !_engineReadyFed && ReferenceEquals(target, A):
|
||||
_engineReadyFed = true;
|
||||
// Feed A's Ready (carries A's idxChangeSeed → receiver seeds _selfXorShiftRandom).
|
||||
ShadowFeed(frame, isPlayerSeat: false, "Ready");
|
||||
// Seed B's XorShift separately — A's Ready doesn't carry B's seed.
|
||||
_engine.SeedOppoIdxChange(BattleSeeds.IdxChange(_state.MasterSeed, B.ViewerId));
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void ShadowFeed(MsgEnvelope frame, bool isPlayerSeat, string label)
|
||||
{
|
||||
var engineFrame = frame.Body is RawBody ? frame : frame with { Body = ToRawBody(frame.Body) };
|
||||
var r = _engine.Receive(engineFrame, isPlayerSeat);
|
||||
if (r.Diverged)
|
||||
_log.LogWarning("BattleSession {Bid}: shadow engine diverged on {Label} feed: {Reason}",
|
||||
BattleId, label, r.RejectReason);
|
||||
if (frame.Uri is NetworkBattleUri.Deal or NetworkBattleUri.Swap or NetworkBattleUri.Ready)
|
||||
LogEngineHandState(frame.Uri, $"ShadowFeed({label})");
|
||||
}
|
||||
|
||||
private static readonly JsonSerializerOptions _bodyJsonOptions = Wire.WireJsonOptions.CamelCase;
|
||||
|
||||
/// <summary>Convert a typed body record (DealBody, SwapResponseBody, ReadyBody, etc.) to the
|
||||
/// <see cref="RawBody"/> the engine receiver expects. Serialize → JsonElement → ToObject (the
|
||||
/// same deep-conversion MsgEnvelope.FromJson uses for incoming wire frames).</summary>
|
||||
private static RawBody ToRawBody(IMsgBody? body)
|
||||
{
|
||||
if (body is null) return new RawBody(new Dictionary<string, object?>());
|
||||
var el = JsonSerializer.SerializeToElement(body, body.GetType(), _bodyJsonOptions);
|
||||
var dict = el.EnumerateObject()
|
||||
.ToDictionary(p => p.Name, p => MsgEnvelope.ToObject(p.Value));
|
||||
return new RawBody(dict);
|
||||
}
|
||||
|
||||
/// <summary>Seat the shadow engine once, from the master seed + both deterministically-shuffled
|
||||
/// decks the node already computed (F-N-5). Attempted a single time; if the host can't seat the
|
||||
/// engine headless, it stays not-ready and the shadow no-ops for the rest of the battle.</summary>
|
||||
@@ -268,7 +361,16 @@ public sealed class BattleSession
|
||||
return;
|
||||
}
|
||||
_engineOwned = true;
|
||||
_engine.Setup(_state.MasterSeed,
|
||||
// Seed the engine's StableRandom with BattleSeeds.Stable(MasterSeed) — the SAME value the
|
||||
// Matched frame ships to both clients (InitBattleHandler.cs:28). The clients seed their
|
||||
// System.Random with Matched.seed (BattleManagerBase.cs:721), so the engine's stream must
|
||||
// share that derivation to track. MasterSeed itself is a root only — every wire-facing seed
|
||||
// (Stable, IdxChange, DeckShuffle) is a BattleSeeds.Derive(...) of it; the engine never
|
||||
// consumes the root directly. Live regression: bid 654473755566 had MasterSeed=1184631275
|
||||
// and Stable=1543475792 (the Matched.seed); seeding the engine with the raw root made every
|
||||
// turn-1+ draw pick a different deck position than the clients, so the opponent's first
|
||||
// non-mulligan play addressed a card the engine never drew → HandCardToField threw.
|
||||
_engine.Setup(BattleSeeds.Stable(_state.MasterSeed),
|
||||
_state.GetShuffledDeck(A), _state.GetShuffledDeck(B),
|
||||
(int)A.Context.ClassId, (int)B.Context.ClassId);
|
||||
}
|
||||
@@ -279,8 +381,21 @@ public sealed class BattleSession
|
||||
bool isPlayerSeat = ReferenceEquals(from, A);
|
||||
var r = _engine.Receive(env, isPlayerSeat);
|
||||
if (r.Diverged)
|
||||
_log.LogInformation("BattleSession {Bid}: shadow engine diverged on {Uri}: {Reason}",
|
||||
_log.LogWarning("BattleSession {Bid}: shadow engine diverged on {Uri}: {Reason}",
|
||||
BattleId, env.Uri, r.RejectReason);
|
||||
if (env.Uri is NetworkBattleUri.Swap or NetworkBattleUri.TurnStart or NetworkBattleUri.PlayActions)
|
||||
LogEngineHandState(env.Uri, $"ShadowIngest(seat={(isPlayerSeat ? "A" : "B")})");
|
||||
}
|
||||
|
||||
private void LogEngineHandState(NetworkBattleUri uri, string label)
|
||||
{
|
||||
if (!_engine.IsReady) return;
|
||||
var aIdxs = string.Join(",", Enumerable.Range(0, _engine.HandCount(true))
|
||||
.Select(i => _engine.HandCardIndex(true, i)));
|
||||
var bIdxs = string.Join(",", Enumerable.Range(0, _engine.HandCount(false))
|
||||
.Select(i => _engine.HandCardIndex(false, i)));
|
||||
_log.LogInformation("BattleSession {Bid}: engine hand after {Uri} {Label}: A=[{AHand}] B=[{BHand}]",
|
||||
BattleId, uri, label, aIdxs, bIdxs);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user