From 530b56c33c6215cf4211db09990af0573b442454 Mon Sep 17 00:00:00 2001 From: dingo Date: Wed, 18 Mar 2026 20:02:10 -0400 Subject: [PATCH] =?UTF-8?q?Fix:=20ghost-match=20bug=20=E2=80=94=20session?= =?UTF-8?q?=20stays=20Active=20after=20game=20ends?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Two root causes fixed: 1. Race condition (primary cause): SaveStateAsync committed the transaction with Phase=GameOver in StateJson, but session.Status was not set to Completed until a separate SaveChangesAsync in FinalizeGameAsync. If the server crashed or any exception was thrown between those two calls, the session was left Active with a GameOver state — causing the "active game" prompt on next login. Fix: each game-over handler (concede, force_concede, attack) now sets session.Status/WinnerAccountId/WinCondition/EndedAt BEFORE calling SaveStateAsync, so all fields commit atomically in the same transaction. 2. Wrong save order in FinalizeGameAsync: identityDb.SaveChangesAsync (ELO update) ran before gameDb.SaveChangesAsync (Status=Completed). Any transient identity-DB error left the session permanently Active. Fix: gameDb is saved first; ELO runs after, so a failed ELO update never causes a ghost match. 3. Defensive startup heal (GameStartupCleanupService): on server start, Active sessions whose StateJson contains Phase=GameOver are now detected and marked Completed. game.over is pushed to any still-connected clients so they can exit cleanly. Generated with [Claude Code](https://claude.ai/code) via [Happy](https://happy.engineering) Co-Authored-By: Claude Co-Authored-By: Happy --- .../src/SOR.Game/GameStartupCleanupService.cs | 124 +++++++++++++----- .../SOR.Game/Handlers/GameAttackHandler.cs | 18 ++- .../SOR.Game/Handlers/GameConcedeHandler.cs | 17 ++- .../Handlers/GameForceConcedeHandler.cs | 8 ++ .../src/SOR.Game/Handlers/GameHandlerBase.cs | 9 +- 5 files changed, 140 insertions(+), 36 deletions(-) diff --git a/Server/src/SOR.Game/GameStartupCleanupService.cs b/Server/src/SOR.Game/GameStartupCleanupService.cs index 8972859..559bd76 100644 --- a/Server/src/SOR.Game/GameStartupCleanupService.cs +++ b/Server/src/SOR.Game/GameStartupCleanupService.cs @@ -54,55 +54,119 @@ internal sealed class GameStartupCleanupService : IHostedService // Sessions created in the last 60 s may still be mid-handshake. var staleThreshold = DateTimeOffset.UtcNow.AddSeconds(-StaleThresholdSeconds); + // ── 1. Abandon stale Initializing sessions ──────────────────────────── + var stuck = await gameDb.GameSessions .Where(s => s.Status == GameSessionStatus.Initializing && s.CreatedAt <= staleThreshold) .ToListAsync(cancellationToken); - if (stuck.Count == 0) - return; - - _logger.LogWarning( - "Startup cleanup: abandoning {Count} Initializing session(s) left over from previous process.", - stuck.Count); - - var now = DateTimeOffset.UtcNow; - var push = new GameSessionAbandonedPush(Guid.Empty, "server_restart"); - - foreach (var session in stuck) + if (stuck.Count > 0) { - session.Status = GameSessionStatus.Abandoned; - session.EndedAt = now; - session.WinCondition = "server_restart"; + _logger.LogWarning( + "Startup cleanup: abandoning {Count} Initializing session(s) left over from previous process.", + stuck.Count); - // Best-effort push — clients on the loading screen will get a signal to - // return to menu. Ignore errors so a bad Redis connection doesn't block - // the rest of the cleanup or prevent the service from starting. + var now = DateTimeOffset.UtcNow; + var push = new GameSessionAbandonedPush(Guid.Empty, "server_restart"); + + foreach (var session in stuck) + { + session.Status = GameSessionStatus.Abandoned; + session.EndedAt = now; + session.WinCondition = "server_restart"; + + // Best-effort push — clients on the loading screen will get a signal to + // return to menu. Ignore errors so a bad Redis connection doesn't block + // the rest of the cleanup or prevent the service from starting. + try + { + var sessionPush = push with { SessionId = session.Id }; + await Task.WhenAll( + clientPush.PushAsync( + session.PlayerOneAccountId.ToString(), + ServerMessage.Push("game.session_abandoned", sessionPush), + cancellationToken), + clientPush.PushAsync( + session.PlayerTwoAccountId.ToString(), + ServerMessage.Push("game.session_abandoned", sessionPush), + cancellationToken)); + } + catch (Exception ex) + { + _logger.LogWarning(ex, + "Could not push session_abandoned for session {SessionId}; clients will time out naturally.", + session.Id); + } + } + } + + // ── 2. Heal ghost-Active sessions (StateJson has Phase=GameOver but Status=Active) ── + // + // These are left behind when the server crashes in the narrow window between + // SaveStateAsync committing the state and FinalizeGameAsync saving the status. + // They show up as "active game" on the player's next login even though the game + // is truly over. We can't award ELO retroactively, so we just mark Completed + // and push game.over with zeroed deltas so both clients can return to the menu. + + var ghostActive = await gameDb.GameSessions + .Where(s => s.Status == GameSessionStatus.Active && s.StateJson != null) + .ToListAsync(cancellationToken); + + var ghostCount = 0; + foreach (var session in ghostActive) + { try { - var sessionPush = push with { SessionId = session.Id }; - await Task.WhenAll( - clientPush.PushAsync( - session.PlayerOneAccountId.ToString(), - ServerMessage.Push("game.session_abandoned", sessionPush), - cancellationToken), - clientPush.PushAsync( - session.PlayerTwoAccountId.ToString(), - ServerMessage.Push("game.session_abandoned", sessionPush), - cancellationToken)); + var state = GameEngine.Deserialize(session.StateJson!); + if (state.Phase != GamePhase.GameOver) continue; + + _logger.LogWarning( + "Startup cleanup: session {SessionId} is Active but StateJson has Phase=GameOver — marking Completed.", + session.Id); + + session.Status = GameSessionStatus.Completed; + session.EndedAt ??= DateTimeOffset.UtcNow; + // WinnerAccountId may already be set if the crash was after setting it; leave it. + + ghostCount++; + + // Push game.over so any still-connected clients can exit cleanly. + try + { + var ghostPush = new GameOverPush( + SessionId : session.Id, + WinnerAccountId : session.WinnerAccountId ?? Guid.Empty, + LoserAccountId : Guid.Empty, + WinCondition : session.WinCondition ?? "server_restart", + WinnerRankDelta : 0, + LoserRankDelta : 0, + WinnerOpDelta : 0, + LoserOpDelta : 0); + await Task.WhenAll( + clientPush.PushAsync(session.PlayerOneAccountId.ToString(), + ServerMessage.Push("game.over", ghostPush), cancellationToken), + clientPush.PushAsync(session.PlayerTwoAccountId.ToString(), + ServerMessage.Push("game.over", ghostPush), cancellationToken)); + } + catch (Exception ex) + { + _logger.LogWarning(ex, + "Could not push game.over for ghost session {SessionId}.", session.Id); + } } catch (Exception ex) { _logger.LogWarning(ex, - "Could not push session_abandoned for session {SessionId}; clients will time out naturally.", - session.Id); + "Could not process ghost session {SessionId} during startup cleanup.", session.Id); } } await gameDb.SaveChangesAsync(cancellationToken); _logger.LogInformation( - "Startup cleanup complete: {Count} session(s) abandoned.", stuck.Count); + "Startup cleanup complete: {InitCount} Initializing session(s) abandoned, {GhostCount} ghost Active session(s) healed.", + stuck.Count, ghostCount); } public Task StopAsync(CancellationToken cancellationToken) => Task.CompletedTask; diff --git a/Server/src/SOR.Game/Handlers/GameAttackHandler.cs b/Server/src/SOR.Game/Handlers/GameAttackHandler.cs index af07b29..4198118 100644 --- a/Server/src/SOR.Game/Handlers/GameAttackHandler.cs +++ b/Server/src/SOR.Game/Handlers/GameAttackHandler.cs @@ -2,6 +2,7 @@ namespace SOR.Game.Handlers; using System.Text.Json; using SOR.Database.Contexts; +using SOR.Database.Enums; using SOR.Networking.Abstractions.EventBus; using SOR.Networking.Abstractions.Messaging; using SOR.Networking.Abstractions.Push; @@ -49,13 +50,28 @@ internal sealed class GameAttackHandler : GameHandlerBase, IMessageHandler var (newState, gameOver) = GameEngine.Attack( state, actorId, req.AttackerInstanceId, req.TargetInstanceId); + if (gameOver) + { + // The attacking player destroyed the opponent's ArchSpirit. + // Set completion fields BEFORE SaveStateAsync so they are committed atomically + // with the StateJson update (prevents ghost-match on next login if server crashes + // in the window between SaveStateAsync and FinalizeGameAsync). + var loserId = session.PlayerOneAccountId.ToString() == actorId + ? session.PlayerTwoAccountId + : session.PlayerOneAccountId; + + session.Status = GameSessionStatus.Completed; + session.WinnerAccountId = Guid.Parse(actorId); + session.WinCondition = "health"; + session.EndedAt = DateTimeOffset.UtcNow; + } + var dto = GameEngine.ToDto(newState, actorId); await SaveStateAsync(_gameDb, session, newState, actorId, "game.attack", JsonSerializer.Serialize(req), ct, JsonSerializer.Serialize(dto)); if (gameOver) { - // The attacking player destroyed the opponent's ArchSpirit. var loserId = session.PlayerOneAccountId.ToString() == actorId ? session.PlayerTwoAccountId : session.PlayerOneAccountId; diff --git a/Server/src/SOR.Game/Handlers/GameConcedeHandler.cs b/Server/src/SOR.Game/Handlers/GameConcedeHandler.cs index 0f8594c..dc103bd 100644 --- a/Server/src/SOR.Game/Handlers/GameConcedeHandler.cs +++ b/Server/src/SOR.Game/Handlers/GameConcedeHandler.cs @@ -2,6 +2,7 @@ namespace SOR.Game.Handlers; using System.Text.Json; using SOR.Database.Contexts; +using SOR.Database.Enums; using SOR.Networking.Abstractions.EventBus; using SOR.Networking.Abstractions.Messaging; using SOR.Networking.Abstractions.Push; @@ -47,14 +48,22 @@ internal sealed class GameConcedeHandler : GameHandlerBase, IMessageHandler var state = GameEngine.Deserialize(session.StateJson!); var newState = GameEngine.Concede(state, actorId); - var dto = GameEngine.ToDto(newState, actorId); - await SaveStateAsync(_gameDb, session, newState, actorId, "game.concede", - JsonSerializer.Serialize(req), ct, JsonSerializer.Serialize(dto)); - var winnerId = session.PlayerOneAccountId.ToString() == actorId ? session.PlayerTwoAccountId : session.PlayerOneAccountId; + // Set completion fields BEFORE SaveStateAsync so they are committed atomically + // with the StateJson update. This prevents the race window where StateJson has + // Phase=GameOver but Status is still Active (causing ghost-match on next login). + session.Status = GameSessionStatus.Completed; + session.WinnerAccountId = winnerId; + session.WinCondition = "concede"; + session.EndedAt = DateTimeOffset.UtcNow; + + var dto = GameEngine.ToDto(newState, actorId); + await SaveStateAsync(_gameDb, session, newState, actorId, "game.concede", + JsonSerializer.Serialize(req), ct, JsonSerializer.Serialize(dto)); + await FinalizeGameAsync( _gameDb, _identityDb, _clientPush, _eventBus, session, diff --git a/Server/src/SOR.Game/Handlers/GameForceConcedeHandler.cs b/Server/src/SOR.Game/Handlers/GameForceConcedeHandler.cs index 63f9f51..2159b6c 100644 --- a/Server/src/SOR.Game/Handlers/GameForceConcedeHandler.cs +++ b/Server/src/SOR.Game/Handlers/GameForceConcedeHandler.cs @@ -2,6 +2,7 @@ namespace SOR.Game.Handlers; using System.Text.Json; using SOR.Database.Contexts; +using SOR.Database.Enums; using SOR.Networking.Abstractions.EventBus; using SOR.Networking.Abstractions.Messaging; using SOR.Networking.Abstractions.Push; @@ -69,6 +70,13 @@ internal sealed class GameForceConcedeHandler : GameHandlerBase, IMessageHandler var newState = GameEngine.Concede(state, inactivePlayerId); var dto = GameEngine.ToDto(newState, actorId); + // Set completion fields BEFORE SaveStateAsync so they are committed atomically + // with the StateJson update. + session.Status = GameSessionStatus.Completed; + session.WinnerAccountId = Guid.Parse(actorId); + session.WinCondition = "inactive"; + session.EndedAt = DateTimeOffset.UtcNow; + await SaveStateAsync(_gameDb, session, newState, actorId, "game.force_concede", JsonSerializer.Serialize(req), ct, JsonSerializer.Serialize(dto)); diff --git a/Server/src/SOR.Game/Handlers/GameHandlerBase.cs b/Server/src/SOR.Game/Handlers/GameHandlerBase.cs index 1a821cc..28dbc0a 100644 --- a/Server/src/SOR.Game/Handlers/GameHandlerBase.cs +++ b/Server/src/SOR.Game/Handlers/GameHandlerBase.cs @@ -131,11 +131,19 @@ internal abstract class GameHandlerBase string winCondition, CancellationToken ct) { + // These fields may already be set by the calling handler (so they are committed + // atomically with the StateJson update in SaveStateAsync). Setting them here again + // is idempotent and ensures correctness even if called without the pre-set pattern. session.Status = GameSessionStatus.Completed; session.WinnerAccountId = winnerAccountId; session.WinCondition = winCondition; session.EndedAt = DateTimeOffset.UtcNow; + // Save game session status FIRST — this must succeed before we touch ELO. + // If identity DB fails below, the session is still correctly marked Completed + // so players won't be stuck in a ghost match on next login. + await gameDb.SaveChangesAsync(ct); + // Load both accounts for ELO + OP adjustment. var accounts = await identityDb.Users .Where(a => a.Id == winnerAccountId || a.Id == loserAccountId) @@ -167,7 +175,6 @@ internal abstract class GameHandlerBase loser.OriginPoints += loserOp; await identityDb.SaveChangesAsync(ct); - await gameDb.SaveChangesAsync(ct); var push = new GameOverPush( SessionId : session.Id,