diff --git a/SVSim.BattleNode/Sessions/IBattleSessionStore.cs b/SVSim.BattleNode/Sessions/IBattleSessionStore.cs index 541ead7..1221b79 100644 --- a/SVSim.BattleNode/Sessions/IBattleSessionStore.cs +++ b/SVSim.BattleNode/Sessions/IBattleSessionStore.cs @@ -8,6 +8,16 @@ public interface IBattleSessionStore /// Look up the pending battle. Returns null if not present. PendingBattle? TryGetPending(string battleId); + /// + /// Find a pending battle this viewer is a participant in (P1 or P2). Used by the + /// HTTP-side /ai_<fmt>/start endpoint to retrieve the deck/cosmetic + /// context the viewer registered at do_matching time — the /start + /// request body carries no deck_no of its own. Returns null if the viewer + /// has no pending battle (already consumed by WS connect, never registered, or + /// evicted by timeout). + /// + PendingBattle? TryFindPendingForViewer(long viewerId); + /// Mark a battle as no longer pending (e.g. on successful connect or explicit close). bool RemovePending(string battleId); } diff --git a/SVSim.BattleNode/Sessions/InMemoryBattleSessionStore.cs b/SVSim.BattleNode/Sessions/InMemoryBattleSessionStore.cs index 2f14512..360fa35 100644 --- a/SVSim.BattleNode/Sessions/InMemoryBattleSessionStore.cs +++ b/SVSim.BattleNode/Sessions/InMemoryBattleSessionStore.cs @@ -12,6 +12,21 @@ public sealed class InMemoryBattleSessionStore : IBattleSessionStore public PendingBattle? TryGetPending(string battleId) => _pending.TryGetValue(battleId, out var b) ? b : null; + public PendingBattle? TryFindPendingForViewer(long viewerId) + { + // Linear scan — _pending is bounded by concurrent in-flight matches (low + // double digits at most), so this stays cheap. Returns whichever match the + // dictionary's enumerator yields first; in practice a viewer has at most one + // pending battle since each /do_matching either pairs/falls-back the existing + // slot or parks without registering. + foreach (var b in _pending.Values) + { + if (b.P1.ViewerId == viewerId) return b; + if (b.P2 is not null && b.P2.ViewerId == viewerId) return b; + } + return null; + } + public bool RemovePending(string battleId) => _pending.TryRemove(battleId, out _); } diff --git a/SVSim.EmulatedEntrypoint/Controllers/RankBattleController.cs b/SVSim.EmulatedEntrypoint/Controllers/RankBattleController.cs index 25d305d..9526919 100644 --- a/SVSim.EmulatedEntrypoint/Controllers/RankBattleController.cs +++ b/SVSim.EmulatedEntrypoint/Controllers/RankBattleController.cs @@ -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 _log; @@ -31,12 +33,14 @@ public sealed class RankBattleController : ControllerBase public RankBattleController( IMatchingPairUpService pairUp, IMatchingBridge bridge, + IBattleSessionStore sessionStore, IMatchContextBuilder ctxBuilder, IBotRoster botRoster, ILogger 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_/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); diff --git a/SVSim.EmulatedEntrypoint/Services/IMatchContextBuilder.cs b/SVSim.EmulatedEntrypoint/Services/IMatchContextBuilder.cs index a9da5d0..84c9a83 100644 --- a/SVSim.EmulatedEntrypoint/Services/IMatchContextBuilder.cs +++ b/SVSim.EmulatedEntrypoint/Services/IMatchContextBuilder.cs @@ -18,13 +18,10 @@ public interface IMatchContextBuilder Task BuildForTwoPickAsync(long viewerId); /// - /// 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 do_matching's deck_no). Pulls the + /// viewer's deck for that format/number + viewer cosmetics. Throws if the viewer has + /// no deck at that slot. /// - /// - /// Deck-selection persistence (which deck number is "current" for this format) is a - /// separate concern; deck #1 is a placeholder until that lands. - /// - Task BuildForRankBattleAsync(long viewerId, Format format); + Task BuildForRankBattleAsync(long viewerId, Format format, int deckNo); } diff --git a/SVSim.EmulatedEntrypoint/Services/MatchContextBuilder.cs b/SVSim.EmulatedEntrypoint/Services/MatchContextBuilder.cs index c7a1e1a..7d6fc8a 100644 --- a/SVSim.EmulatedEntrypoint/Services/MatchContextBuilder.cs +++ b/SVSim.EmulatedEntrypoint/Services/MatchContextBuilder.cs @@ -70,17 +70,17 @@ public class MatchContextBuilder : IMatchContextBuilder BattleType: 11); } - public async Task BuildForRankBattleAsync(long viewerId, Format format) + public async Task 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(); var emblemId = viewer.Info.SelectedEmblem.Id != 0 diff --git a/SVSim.UnitTests/BattleNode/Integration/BattleNodeFlowTests.cs b/SVSim.UnitTests/BattleNode/Integration/BattleNodeFlowTests.cs index 01952bd..a88b342 100644 --- a/SVSim.UnitTests/BattleNode/Integration/BattleNodeFlowTests.cs +++ b/SVSim.UnitTests/BattleNode/Integration/BattleNodeFlowTests.cs @@ -418,7 +418,7 @@ public class BattleNodeFlowTests var bridge = factory.Services.GetRequiredService(); using var scope = factory.Services.CreateScope(); var builder = scope.ServiceProvider.GetRequiredService(); - var ctx = await builder.BuildForRankBattleAsync(vid, SVSim.Database.Enums.Format.Rotation); + var ctx = await builder.BuildForRankBattleAsync(vid, SVSim.Database.Enums.Format.Rotation, deckNo: 1); var pending = bridge.RegisterBattle( new SVSim.BattleNode.Bridge.BattlePlayer(vid, ctx), p2: null, diff --git a/SVSim.UnitTests/Controllers/RankBattleControllerTests.cs b/SVSim.UnitTests/Controllers/RankBattleControllerTests.cs index 07853fb..919cd6a 100644 --- a/SVSim.UnitTests/Controllers/RankBattleControllerTests.cs +++ b/SVSim.UnitTests/Controllers/RankBattleControllerTests.cs @@ -2,7 +2,10 @@ using System.Net.Http.Json; using System.Text.Json; using Microsoft.Extensions.DependencyInjection; using NUnit.Framework; +using SVSim.BattleNode.Bridge; +using SVSim.BattleNode.Sessions; using SVSim.Database.Enums; +using SVSim.EmulatedEntrypoint.Services; using SVSim.UnitTests.Infrastructure; namespace SVSim.UnitTests.Controllers; @@ -44,6 +47,21 @@ public class RankBattleControllerTests steam_session_ticket = "", }; + /// + /// AiStart in the real client flow always follows a do_matching call that resolved + /// to 3011 (AI fallback) — that's when the PendingBattle is registered with the + /// viewer's queue-time MatchContext (deck/cosmetics). Tests bypass do_matching's + /// time-threshold to register a Bot PendingBattle directly via the bridge. + /// + private static async Task RegisterBotBattleAsync(SVSimTestFactory factory, long viewerId, Format format, int deckNo) + { + var bridge = factory.Services.GetRequiredService(); + using var scope = factory.Services.CreateScope(); + var builder = scope.ServiceProvider.GetRequiredService(); + var ctx = await builder.BuildForRankBattleAsync(viewerId, format, deckNo); + bridge.RegisterBattle(new BattlePlayer(viewerId, ctx), p2: null, BattleType.Bot); + } + [Test] public async Task DoMatching_rotation_first_poll_returns_3002_RETRY_with_empty_node_server_url() { @@ -102,6 +120,7 @@ public class RankBattleControllerTests var viewerId = await factory.SeedViewerAsync(displayName: "TestViewer"); await factory.SeedGlobalsAsync(); await factory.SeedDeckAsync(viewerId, Format.Rotation, 1); + await RegisterBotBattleAsync(factory, viewerId, Format.Rotation, deckNo: 1); var client = factory.CreateAuthenticatedClient(viewerId); var resp = await client.PostAsJsonAsync("/ai_rotation_rank_battle/start", EmptyAuthedBody); @@ -140,6 +159,7 @@ public class RankBattleControllerTests var viewerId = await factory.SeedViewerAsync(displayName: "Alice"); await factory.SeedGlobalsAsync(); await factory.SeedDeckAsync(viewerId, Format.Rotation, 1); + await RegisterBotBattleAsync(factory, viewerId, Format.Rotation, deckNo: 1); var client = factory.CreateAuthenticatedClient(viewerId); var resp = await client.PostAsJsonAsync("/ai_rotation_rank_battle/start", EmptyAuthedBody); @@ -156,6 +176,7 @@ public class RankBattleControllerTests var viewerId = await factory.SeedViewerAsync(displayName: "PlayerA"); await factory.SeedGlobalsAsync(); await factory.SeedDeckAsync(viewerId, Format.Rotation, 1); + await RegisterBotBattleAsync(factory, viewerId, Format.Rotation, deckNo: 1); var client = factory.CreateAuthenticatedClient(viewerId); var resp = await client.PostAsJsonAsync("/ai_rotation_rank_battle/start", EmptyAuthedBody); @@ -167,6 +188,48 @@ public class RankBattleControllerTests Assert.That(oppoInfo.GetProperty("classId").GetInt32(), Is.InRange(1, 8)); } + [Test] + public async Task AiStart_self_info_class_matches_queued_deck_number() + { + // Regression for the 2026-06-02 "queued Bloodcraft, saw Swordcraft leader" wire bug. + // The original impl rebuilt MatchContext from deck #1 inside AiStart; the fix routes + // it through the PendingBattle the bridge stored at do_matching time (which carries + // the queue-time deck_no). Seed two distinct-class decks and confirm /ai_*/start + // returns the right class for a viewer registered with deck #5. + await using var factory = new SVSimTestFactory(); + var viewerId = await factory.SeedViewerAsync(displayName: "Ranker"); + await factory.SeedGlobalsAsync(); + await factory.SeedDeckAsync(viewerId, Format.Unlimited, number: 1, classId: 1); + await factory.SeedDeckAsync(viewerId, Format.Unlimited, number: 5, classId: 6); + await RegisterBotBattleAsync(factory, viewerId, Format.Unlimited, deckNo: 5); + var client = factory.CreateAuthenticatedClient(viewerId); + + var resp = await client.PostAsJsonAsync("/ai_unlimited_rank_battle/start", EmptyAuthedBody); + using var doc = JsonDocument.Parse(await resp.Content.ReadAsStringAsync()); + var selfInfo = doc.RootElement.GetProperty("self_info"); + + Assert.That(selfInfo.GetProperty("classId").GetInt32(), Is.EqualTo(6), + "Self class must reflect the deck the viewer queued with (deck #5 = Bloodcraft, class 6)."); + } + + [Test] + public async Task AiStart_without_pending_battle_returns_neg1_sentinel() + { + // Defensive: clients always do_matching before ai_start, but if /ai_*/start is hit + // without a registered PendingBattle (server restart, expired match, ...), the spec + // sentinel ai_id=-1 surfaces the "no AI assigned" error in the client. + await using var factory = new SVSimTestFactory(); + var viewerId = await factory.SeedViewerAsync(); + await factory.SeedGlobalsAsync(); + await factory.SeedDeckAsync(viewerId, Format.Rotation, 1); + var client = factory.CreateAuthenticatedClient(viewerId); + + var resp = await client.PostAsJsonAsync("/ai_rotation_rank_battle/start", EmptyAuthedBody); + using var doc = JsonDocument.Parse(await resp.Content.ReadAsStringAsync()); + + Assert.That(doc.RootElement.GetProperty("ai_id").GetInt32(), Is.EqualTo(-1)); + } + [Test] public async Task Finish_emits_stubbed_zeros_with_battle_result_echo() { diff --git a/SVSim.UnitTests/Infrastructure/SVSimTestFactory.cs b/SVSim.UnitTests/Infrastructure/SVSimTestFactory.cs index 199d2c1..ce65536 100644 --- a/SVSim.UnitTests/Infrastructure/SVSimTestFactory.cs +++ b/SVSim.UnitTests/Infrastructure/SVSimTestFactory.cs @@ -369,13 +369,16 @@ internal sealed class SVSimTestFactory : WebApplicationFactory /// path. Picks the first seeded class/sleeve/leader-skin from the master tables; tests /// that need specific ids should hit the DB directly. /// - public async Task SeedDeckAsync(long viewerId, Format format, int number, string name = "Test Deck") + public async Task SeedDeckAsync(long viewerId, Format format, int number, string name = "Test Deck", int? classId = null) { using var scope = Services.CreateScope(); var db = scope.ServiceProvider.GetRequiredService(); var repo = scope.ServiceProvider.GetRequiredService(); - var cls = await db.Classes.FirstAsync(); + var cls = classId is null + ? await db.Classes.FirstAsync() + : await db.Classes.FindAsync(classId.Value) + ?? throw new InvalidOperationException($"SeedDeckAsync: class {classId} not found"); var sleeve = await db.Sleeves.FirstAsync(); var skin = await db.LeaderSkins.FirstAsync(); diff --git a/SVSim.UnitTests/Services/MatchContextBuilderTests.cs b/SVSim.UnitTests/Services/MatchContextBuilderTests.cs index a2018c6..56b76d1 100644 --- a/SVSim.UnitTests/Services/MatchContextBuilderTests.cs +++ b/SVSim.UnitTests/Services/MatchContextBuilderTests.cs @@ -128,7 +128,7 @@ public class MatchContextBuilderTests using var scope = factory.Services.CreateScope(); var builder = scope.ServiceProvider.GetRequiredService(); - var ctx = await builder.BuildForRankBattleAsync(viewerId, Format.Rotation); + var ctx = await builder.BuildForRankBattleAsync(viewerId, Format.Rotation, deckNo: 1); Assert.That(ctx.UserName, Is.EqualTo("Ranker")); Assert.That(ctx.BattleType, Is.EqualTo(11), "BattleType=11 matches the prod rank-battle wire value (same as TK2)."); @@ -148,10 +148,33 @@ public class MatchContextBuilderTests using var scope = factory.Services.CreateScope(); var builder = scope.ServiceProvider.GetRequiredService(); - Assert.That(async () => await builder.BuildForRankBattleAsync(viewerId, Format.Rotation), + Assert.That(async () => await builder.BuildForRankBattleAsync(viewerId, Format.Rotation, deckNo: 1), Throws.Exception); } + [Test] + public async Task BuildForRankBattle_uses_the_caller_supplied_deck_number() + { + // Regression for the 2026-06-02 "queued Bloodcraft, saw Swordcraft leader" + // wire bug — MatchContextBuilder.BuildForRankBattleAsync hardcoded deckNo=1. + // Seed two decks for different classes (1 and 6) and confirm the deckNo + // argument picks the right one. + await using var factory = new SVSimTestFactory(); + var viewerId = await factory.SeedViewerAsync(displayName: "Ranker"); + await factory.SeedGlobalsAsync(); + await factory.SeedDeckAsync(viewerId, Format.Unlimited, number: 1, name: "Deck 1", classId: 1); + await factory.SeedDeckAsync(viewerId, Format.Unlimited, number: 5, name: "Deck 5", classId: 6); + + using var scope = factory.Services.CreateScope(); + var builder = scope.ServiceProvider.GetRequiredService(); + + var deck1Ctx = await builder.BuildForRankBattleAsync(viewerId, Format.Unlimited, deckNo: 1); + var deck5Ctx = await builder.BuildForRankBattleAsync(viewerId, Format.Unlimited, deckNo: 5); + + Assert.That(deck1Ctx.ClassId, Is.EqualTo("1"), "deckNo=1 → class 1."); + Assert.That(deck5Ctx.ClassId, Is.EqualTo("6"), "deckNo=5 → class 6 (the wire-bug case)."); + } + [Test] public async Task BuildForTwoPick_falls_back_to_default_loadout_when_unequipped() {