fix(rank-battle): route ai-start through the queue-time MatchContext

Live-smoke bug 2026-06-02: queued Bloodcraft (deck #5), wire showed
classId=2 (Swordcraft) for self_info on the /ai_unlimited_rank_battle/start
response — client rendered the wrong leader.

Two layers of the same bug:

1. MatchContextBuilder.BuildForRankBattleAsync hardcoded deckNo=1 instead
   of taking it from the do_matching request — verified against
   data_dumps/captures/traffic.ndjson L17 where deck_no=5 was on the wire.
   Signature changes to (viewerId, format, deckNo); DoMatchingInternal
   passes req.DeckNo.

2. AiStartInternal rebuilt MatchContext from scratch — but the /ai_*/start
   request body is BaseRequest only, no deck_no on the wire. The fix uses
   the MatchContext the bridge already stored at do_matching resolution time
   (in the Bot PendingBattle), so deck/cosmetic data is consistent end-to-end.
   New IBattleSessionStore.TryFindPendingForViewer(viewerId) finds the
   viewer's pending battle for lookup. The store entry persists across
   ai_start (idempotent reads are fine — the WS handler removes on connect).
   No-pending sentinel: ai_id=-1 surfaces the "no AI assigned" error in the
   client.

Tests: 936 → 939 passing.
- MatchContextBuilderTests.BuildForRankBattle_uses_the_caller_supplied_deck_number
  seeds deck #1 (class 1) and deck #5 (class 6) and asserts the deckNo
  argument picks the right one.
- RankBattleControllerTests.AiStart_self_info_class_matches_queued_deck_number
  is the end-to-end regression: register Bot battle with deck #5, hit
  /ai_unlimited_rank_battle/start, assert self_info.classId == 6.
- RankBattleControllerTests.AiStart_without_pending_battle_returns_neg1_sentinel
  locks the defensive ai_id=-1 path.
- Existing AiStart_* tests bypass do_matching, so adapted to call a new
  RegisterBotBattleAsync helper that mirrors what InProcessPairUp does on
  AI-fallback resolution.

SeedDeckAsync gains an optional classId so test cases can differentiate
decks by class (was always picking Classes.First()).

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
This commit is contained in:
gamer147
2026-06-02 12:28:42 -04:00
parent 24f9b2240e
commit 898b872edd
9 changed files with 150 additions and 34 deletions

View File

@@ -1,6 +1,7 @@
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using SVSim.BattleNode.Bridge;
using SVSim.BattleNode.Sessions;
using SVSim.Database.Enums;
using SVSim.EmulatedEntrypoint.Constants;
using SVSim.EmulatedEntrypoint.Matching;
@@ -24,6 +25,7 @@ public sealed class RankBattleController : ControllerBase
{
private readonly IMatchingPairUpService _pairUp;
private readonly IMatchingBridge _bridge;
private readonly IBattleSessionStore _sessionStore;
private readonly IMatchContextBuilder _ctxBuilder;
private readonly IBotRoster _botRoster;
private readonly ILogger<RankBattleController> _log;
@@ -31,12 +33,14 @@ public sealed class RankBattleController : ControllerBase
public RankBattleController(
IMatchingPairUpService pairUp,
IMatchingBridge bridge,
IBattleSessionStore sessionStore,
IMatchContextBuilder ctxBuilder,
IBotRoster botRoster,
ILogger<RankBattleController> log)
{
_pairUp = pairUp;
_bridge = bridge;
_sessionStore = sessionStore;
_ctxBuilder = ctxBuilder;
_botRoster = botRoster;
_log = log;
@@ -120,14 +124,14 @@ public sealed class RankBattleController : ControllerBase
MatchContext ctx;
try
{
ctx = await _ctxBuilder.BuildForRankBattleAsync(vid, format);
ctx = await _ctxBuilder.BuildForRankBattleAsync(vid, format, req.DeckNo);
}
catch (InvalidOperationException ex)
{
// Most likely cause: viewer has no deck for this format. Surface as 3001
// RC_BATTLE_MATCHING_ILLEGAL — the client shows the standard matchmaking-error
// dialog rather than retrying forever.
_log.LogWarning(ex, "BuildForRankBattleAsync failed for viewer {Vid} format {Fmt}; returning 3001.", vid, format);
// Most likely cause: viewer has no deck at that slot for this format. Surface
// as 3001 RC_BATTLE_MATCHING_ILLEGAL — the client shows the standard
// matchmaking-error dialog rather than retrying forever.
_log.LogWarning(ex, "BuildForRankBattleAsync failed for viewer {Vid} format {Fmt} deckNo {DeckNo}; returning 3001.", vid, format, req.DeckNo);
return Ok(new DoMatchingResponseDto { MatchingState = 3001, NodeServerUrl = "" });
}
@@ -167,18 +171,19 @@ public sealed class RankBattleController : ControllerBase
{
if (!TryGetViewerId(out var vid)) return Unauthorized();
MatchContext selfCtx;
try
// The /ai_<fmt>/start request body is BaseRequest only — it carries no deck_no.
// The deck the viewer queued with was captured in the PendingBattle's MatchContext
// at /do_matching resolution time (when InProcessPairUp called bridge.RegisterBattle).
// Reuse that context so SelfInfo's classId/charaId/sleeveId match what the user
// actually picked. Rebuilding from deck #1 was the 2026-06-02 wire-bug — surfaced
// as "queued Bloodcraft, saw Swordcraft leader."
var pending = _sessionStore.TryFindPendingForViewer(vid);
if (pending is null)
{
selfCtx = await _ctxBuilder.BuildForRankBattleAsync(vid, format);
}
catch (InvalidOperationException ex)
{
// No deck → can't build a self profile. Surface as the "no AI assigned"
// sentinel; the client treats ai_id=-1 as a fallback/error condition.
_log.LogWarning(ex, "AiStart failed for viewer {Vid} format {Fmt}; returning ai_id=-1.", vid, format);
_log.LogWarning("AiStart for viewer {Vid} format {Fmt} has no pending battle; returning ai_id=-1.", vid, format);
return Ok(new AiBattleStartResponseDto { AiId = -1 });
}
var selfCtx = pending.P1.Context;
var bot = await _botRoster.PickAsync(selfCtx, ct);

View File

@@ -18,13 +18,10 @@ public interface IMatchContextBuilder
Task<MatchContext> BuildForTwoPickAsync(long viewerId);
/// <summary>
/// Build a context for a rank-battle viewer + format (rotation / unlimited). Pulls the
/// viewer's deck #1 for that format + viewer cosmetics. Throws if the viewer has no
/// deck registered for the format.
/// Build a context for a rank-battle viewer + format (rotation / unlimited) + the
/// caller-selected deck number (from <c>do_matching</c>'s <c>deck_no</c>). Pulls the
/// viewer's deck for that format/number + viewer cosmetics. Throws if the viewer has
/// no deck at that slot.
/// </summary>
/// <remarks>
/// Deck-selection persistence (which deck number is "current" for this format) is a
/// separate concern; deck #1 is a placeholder until that lands.
/// </remarks>
Task<MatchContext> BuildForRankBattleAsync(long viewerId, Format format);
Task<MatchContext> BuildForRankBattleAsync(long viewerId, Format format, int deckNo);
}

View File

@@ -70,17 +70,17 @@ public class MatchContextBuilder : IMatchContextBuilder
BattleType: 11);
}
public async Task<MatchContext> BuildForRankBattleAsync(long viewerId, Format format)
public async Task<MatchContext> BuildForRankBattleAsync(long viewerId, Format format, int deckNo)
{
var viewer = await _viewers.LoadForMatchContextAsync(viewerId)
?? throw new InvalidOperationException($"viewer {viewerId} not found");
// Per spec, deck-selection persistence (which deck number is "current" for this
// format) is a separate concern; #1 is a placeholder until that lands. IDeckRepository
// is the right path here — viewer-graph nav refs (DeckCard.Card) don't auto-load
// (see project_ef_nav_include_pitfall memory), which would silently ship card_id=0.
var deck = await _decks.GetDeck(viewerId, format, deckNo: 1)
?? throw new InvalidOperationException($"viewer {viewerId} has no deck for format {format}");
// IDeckRepository is the right path here — viewer-graph nav refs (DeckCard.Card)
// don't auto-load (see project_ef_nav_include_pitfall memory), which would
// silently ship card_id=0.
var deck = await _decks.GetDeck(viewerId, format, deckNo)
?? throw new InvalidOperationException(
$"viewer {viewerId} has no deck #{deckNo} for format {format}");
var defaults = _config.Get<DefaultLoadoutConfig>();
var emblemId = viewer.Info.SelectedEmblem.Id != 0