fix(ai): replace event-driven turns with per-session polling loop
AiPlayerSession now drives its own execution via RunAsync(): - Sends game.ready, then polls DB state every 1 s - IsMyTurn(): Placement = AI hasn't placed yet (simultaneous); Draw/Main = AI is the active player - On turn detection: fires ExecuteTurnAsync in background, backs off to 10 s re-check (watchdog against silent failures) - Interlocked guard prevents concurrent turn execution - Exits cleanly on Completed/Abandoned session or GameOver phase AiPlayerSessionManager starts RunAsync instead of SendReadyAsync, and drops the AiTurnStartedEvent consumer entirely — polling is resilient to missed events and handles placement without needing GamePlaceArchSpiritHandler to publish a turn trigger. Generated with [Claude Code](https://claude.ai/code) via [Happy](https://happy.engineering) Co-Authored-By: Claude <noreply@anthropic.com> Co-Authored-By: Happy <yesreply@happy.engineering>
This commit is contained in:
@@ -1,6 +1,7 @@
|
||||
namespace SOR.Ai.Core;
|
||||
|
||||
using System.Text.Json;
|
||||
using System.Threading;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using Microsoft.Extensions.Logging;
|
||||
@@ -8,7 +9,7 @@ using SOR.Ai.Engine;
|
||||
using SOR.Ai.Heuristics;
|
||||
using SOR.Ai.Transport;
|
||||
using SOR.Database.Contexts;
|
||||
using SOR.Database.Enums; // GamePhase
|
||||
using SOR.Database.Enums; // GamePhase, GameSessionStatus
|
||||
using SOR.Game; // GameState, GameEngine, game request records
|
||||
using SOR.Networking.Abstractions.Messaging;
|
||||
using SOR.Networking.Abstractions.Transport;
|
||||
@@ -16,13 +17,14 @@ using SOR.Networking.Abstractions.Transport;
|
||||
/// <summary>
|
||||
/// Manages one AI-controlled seat in a single active GameSession.
|
||||
///
|
||||
/// Responsibilities:
|
||||
/// - Submits game.ready at startup so the game can begin.
|
||||
/// - Executes the AI's full turn when AiPlayerSessionManager signals it.
|
||||
/// Lifecycle:
|
||||
/// RunAsync → SendReadyAsync → polling loop
|
||||
///
|
||||
/// Phase 1: placed ArchSpirit randomly; ended turn immediately.
|
||||
/// Phase 2: selects a decision engine based on Difficulty, computes a full
|
||||
/// action plan, and submits each action with human-like timing delays.
|
||||
/// The polling loop checks DB state every second. When it's this AI's turn
|
||||
/// (Placement: hasn't placed yet; Draw/Main: active player is this AI) it fires
|
||||
/// ExecuteTurnAsync in a background task and backs off to a 10 s re-check interval.
|
||||
/// The 10 s re-check acts as a watchdog: if ExecuteTurnAsync silently fails the
|
||||
/// next poll will re-trigger. Interlocked guards against concurrent execution.
|
||||
/// </summary>
|
||||
internal sealed class AiPlayerSession : IAsyncDisposable
|
||||
{
|
||||
@@ -30,6 +32,9 @@ internal sealed class AiPlayerSession : IAsyncDisposable
|
||||
private readonly ILogger<AiPlayerSession> _logger;
|
||||
private readonly CancellationTokenSource _sessionCts = new();
|
||||
|
||||
/// <summary>0 = idle, 1 = turn in progress. Prevents concurrent turn execution.</summary>
|
||||
private int _turnInProgress;
|
||||
|
||||
public Guid SessionId { get; }
|
||||
public string AiAccountId { get; }
|
||||
public int Difficulty { get; }
|
||||
@@ -57,41 +62,86 @@ internal sealed class AiPlayerSession : IAsyncDisposable
|
||||
// ── Public API ────────────────────────────────────────────────────────────
|
||||
|
||||
/// <summary>
|
||||
/// Sends game.ready on behalf of the AI after a short humanizing delay.
|
||||
/// Called once when the game session is detected by AiPlayerSessionManager.
|
||||
/// Sends game.ready then enters the polling loop until the game ends or the
|
||||
/// session is cancelled. Called by AiPlayerSessionManager as a fire-and-forget Task.
|
||||
/// </summary>
|
||||
public async Task SendReadyAsync(CancellationToken appCt)
|
||||
public async Task RunAsync(CancellationToken appCt)
|
||||
{
|
||||
using var cts = CancellationTokenSource.CreateLinkedTokenSource(appCt, _sessionCts.Token);
|
||||
var ct = cts.Token;
|
||||
|
||||
await Task.Delay(Random.Shared.Next(300, 900), ct);
|
||||
await SendReadyAsync(ct);
|
||||
|
||||
_logger.LogDebug("AI {Account} sending game.ready for session {Session}.",
|
||||
_logger.LogDebug("AI {Account} polling loop started for session {Session}.",
|
||||
AiAccountId, SessionId);
|
||||
|
||||
await InvokeHandlerAsync("game.ready",
|
||||
JsonSerializer.SerializeToUtf8Bytes(new { SessionId }),
|
||||
ct);
|
||||
while (!ct.IsCancellationRequested)
|
||||
{
|
||||
try
|
||||
{
|
||||
var (state, status) = await ReloadAsync(ct);
|
||||
|
||||
if (status is GameSessionStatus.Completed or GameSessionStatus.Abandoned)
|
||||
break;
|
||||
|
||||
if (status != GameSessionStatus.Active || state is null)
|
||||
{
|
||||
await Task.Delay(1_000, ct);
|
||||
continue;
|
||||
}
|
||||
|
||||
if (state.Phase == GamePhase.GameOver)
|
||||
break;
|
||||
|
||||
if (IsMyTurn(state) &&
|
||||
Interlocked.CompareExchange(ref _turnInProgress, 1, 0) == 0)
|
||||
{
|
||||
// Capture state snapshot for the background task.
|
||||
var capturedState = state;
|
||||
_ = Task.Run(async () =>
|
||||
{
|
||||
try { await ExecuteTurnAsync(capturedState, appCt); }
|
||||
finally { Interlocked.Exchange(ref _turnInProgress, 0); }
|
||||
}, ct);
|
||||
|
||||
// Back off while executing; re-check after 10 s as a watchdog.
|
||||
await Task.Delay(10_000, ct);
|
||||
}
|
||||
else
|
||||
{
|
||||
// Not our turn — poll frequently.
|
||||
await Task.Delay(1_000, ct);
|
||||
}
|
||||
}
|
||||
catch (OperationCanceledException) { break; }
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogWarning(ex, "AI {Account}: polling loop error.", AiAccountId);
|
||||
await Task.Delay(2_000, ct);
|
||||
}
|
||||
}
|
||||
|
||||
_logger.LogDebug("AI {Account} polling loop ended for session {Session}.",
|
||||
AiAccountId, SessionId);
|
||||
}
|
||||
|
||||
// ── Turn logic ────────────────────────────────────────────────────────────
|
||||
|
||||
/// <summary>
|
||||
/// Executes the AI's full turn.
|
||||
///
|
||||
/// Selects the decision engine based on the difficulty profile, computes
|
||||
/// an action plan, then submits each action with human-like delays.
|
||||
/// Placement phase is handled separately (random coord from starting zone).
|
||||
/// Executes the AI's full turn for the given phase snapshot.
|
||||
/// For Draw phase: draws first, reloads state, then computes the Main phase plan.
|
||||
/// For Placement phase: places ArchSpirit at a random starting zone tile.
|
||||
/// </summary>
|
||||
public async Task ExecuteTurnAsync(GameState state, CancellationToken appCt)
|
||||
private async Task ExecuteTurnAsync(GameState state, CancellationToken appCt)
|
||||
{
|
||||
using var cts = CancellationTokenSource.CreateLinkedTokenSource(appCt, _sessionCts.Token);
|
||||
var ct = cts.Token;
|
||||
|
||||
_logger.LogDebug(
|
||||
"AI {Account} (seat {Seat}) taking turn {Turn} in session {Session}.",
|
||||
AiAccountId, SeatIndex, state.TurnNumber, SessionId);
|
||||
"AI {Account} (seat {Seat}) taking turn — phase {Phase}, turn {Turn}, session {Session}.",
|
||||
AiAccountId, SeatIndex, state.Phase, state.TurnNumber, SessionId);
|
||||
|
||||
// Placement phase: place ArchSpirit before everything else.
|
||||
// ── Placement ─────────────────────────────────────────────────────────
|
||||
if (state.Phase == GamePhase.Placement)
|
||||
{
|
||||
await ExecutePlacementAsync(state, ct);
|
||||
@@ -101,10 +151,10 @@ internal sealed class AiPlayerSession : IAsyncDisposable
|
||||
// Resolve difficulty profile + strategy overlay.
|
||||
var profile = AiDifficultyProfiles.Get(Difficulty).WithStrategy(Strategy);
|
||||
|
||||
// Draw phase: send game.draw, then reload state so the plan is computed
|
||||
// with the actual hand contents after drawing (Main phase state).
|
||||
// ── Draw phase ────────────────────────────────────────────────────────
|
||||
// ActionCandidateGenerator.All returns only [AiDrawAction] during Draw phase,
|
||||
// so computing the plan before drawing would always produce [draw, end_turn].
|
||||
// so computing the plan before drawing always produces [draw, end_turn].
|
||||
// Draw first, reload state, then fall through to the Main phase plan.
|
||||
if (state.Phase == GamePhase.Draw)
|
||||
{
|
||||
await Task.Delay(Random.Shared.Next(300, 700), ct);
|
||||
@@ -113,8 +163,8 @@ internal sealed class AiPlayerSession : IAsyncDisposable
|
||||
JsonSerializer.SerializeToUtf8Bytes(new GameDrawRequest(SessionId)),
|
||||
ct);
|
||||
|
||||
// Reload state: the draw handler updated StateJson in the DB.
|
||||
var reloaded = await ReloadStateAsync(ct);
|
||||
// Reload: the draw handler has committed the new StateJson to the DB.
|
||||
var (reloaded, _) = await ReloadAsync(ct);
|
||||
if (reloaded is null)
|
||||
{
|
||||
_logger.LogWarning("AI {Account}: could not reload state after draw.", AiAccountId);
|
||||
@@ -126,17 +176,18 @@ internal sealed class AiPlayerSession : IAsyncDisposable
|
||||
if (state.Phase != GamePhase.Main)
|
||||
{
|
||||
_logger.LogDebug(
|
||||
"AI {Account}: state is {Phase} after draw — skipping Main phase plan.",
|
||||
"AI {Account}: phase is {Phase} after draw — not executing Main plan.",
|
||||
AiAccountId, state.Phase);
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
// Think delay (before first Main-phase action).
|
||||
// ── Main phase ────────────────────────────────────────────────────────
|
||||
|
||||
// Think delay before first action.
|
||||
await Task.Delay(
|
||||
Random.Shared.Next(profile.MinThinkTimeMs, profile.MaxThinkTimeMs + 1), ct);
|
||||
|
||||
// Compute action plan with post-draw Main phase state.
|
||||
var ctx = new AiTurnContext(state, AiAccountId);
|
||||
var engine = ResolveEngine(profile);
|
||||
IReadOnlyList<AiAction> plan;
|
||||
@@ -152,7 +203,6 @@ internal sealed class AiPlayerSession : IAsyncDisposable
|
||||
|
||||
_logger.LogDebug("AI {Account} turn plan: {Count} action(s).", AiAccountId, plan.Count);
|
||||
|
||||
// Submit each action with delays.
|
||||
foreach (var action in plan)
|
||||
{
|
||||
ct.ThrowIfCancellationRequested();
|
||||
@@ -162,7 +212,6 @@ internal sealed class AiPlayerSession : IAsyncDisposable
|
||||
|
||||
await InvokeHandlerAsync(msgType, payload, ct);
|
||||
|
||||
// Small delay between sequential actions (except after EndTurn).
|
||||
if (action is not AiEndTurnAction)
|
||||
{
|
||||
await Task.Delay(
|
||||
@@ -171,25 +220,41 @@ internal sealed class AiPlayerSession : IAsyncDisposable
|
||||
}
|
||||
}
|
||||
|
||||
// ── State reload ──────────────────────────────────────────────────────────
|
||||
// ── IsMyTurn ──────────────────────────────────────────────────────────────
|
||||
|
||||
/// <summary>
|
||||
/// Loads the current game state from the DB.
|
||||
/// Used after invoking game.draw to get the post-draw Main-phase state.
|
||||
/// Returns true when this AI seat should act.
|
||||
///
|
||||
/// Placement: simultaneous — true if this AI hasn't placed its ArchSpirit yet.
|
||||
/// Draw/Main: sequential — true when this AI is the active player.
|
||||
/// All other phases (Setup, End, GameOver): false.
|
||||
/// </summary>
|
||||
private async Task<GameState?> ReloadStateAsync(CancellationToken ct)
|
||||
private bool IsMyTurn(GameState state) =>
|
||||
state.Phase switch
|
||||
{
|
||||
GamePhase.Placement =>
|
||||
state.Players.TryGetValue(AiAccountId, out var p) &&
|
||||
p.ArchSpirit?.Position.HasValue != true,
|
||||
|
||||
GamePhase.Draw or GamePhase.Main =>
|
||||
string.Equals(state.ActivePlayerAccountId, AiAccountId,
|
||||
StringComparison.OrdinalIgnoreCase),
|
||||
|
||||
_ => false,
|
||||
};
|
||||
|
||||
// ── game.ready ────────────────────────────────────────────────────────────
|
||||
|
||||
private async Task SendReadyAsync(CancellationToken ct)
|
||||
{
|
||||
using var scope = _scopeFactory.CreateScope();
|
||||
var gameDb = scope.ServiceProvider.GetRequiredService<GameDbContext>();
|
||||
await Task.Delay(Random.Shared.Next(300, 900), ct);
|
||||
|
||||
var session = await gameDb.GameSessions
|
||||
.AsNoTracking()
|
||||
.FirstOrDefaultAsync(s => s.Id == SessionId, ct);
|
||||
_logger.LogDebug("AI {Account} sending game.ready for session {Session}.",
|
||||
AiAccountId, SessionId);
|
||||
|
||||
if (session?.StateJson is null)
|
||||
return null;
|
||||
|
||||
return GameEngine.Deserialize(session.StateJson);
|
||||
await InvokeHandlerAsync("game.ready",
|
||||
JsonSerializer.SerializeToUtf8Bytes(new { SessionId }),
|
||||
ct);
|
||||
}
|
||||
|
||||
// ── Placement ─────────────────────────────────────────────────────────────
|
||||
@@ -226,6 +291,26 @@ internal sealed class AiPlayerSession : IAsyncDisposable
|
||||
ct);
|
||||
}
|
||||
|
||||
// ── State reload ──────────────────────────────────────────────────────────
|
||||
|
||||
private async Task<(GameState? state, GameSessionStatus status)> ReloadAsync(CancellationToken ct)
|
||||
{
|
||||
using var scope = _scopeFactory.CreateScope();
|
||||
var gameDb = scope.ServiceProvider.GetRequiredService<GameDbContext>();
|
||||
|
||||
var session = await gameDb.GameSessions
|
||||
.AsNoTracking()
|
||||
.FirstOrDefaultAsync(s => s.Id == SessionId, ct);
|
||||
|
||||
if (session is null)
|
||||
return (null, GameSessionStatus.Abandoned);
|
||||
|
||||
if (session.StateJson is null)
|
||||
return (null, session.Status);
|
||||
|
||||
return (GameEngine.Deserialize(session.StateJson), session.Status);
|
||||
}
|
||||
|
||||
// ── Engine selection ──────────────────────────────────────────────────────
|
||||
|
||||
private static IAiDecisionEngine ResolveEngine(AiDifficultyProfile profile) =>
|
||||
@@ -239,10 +324,6 @@ internal sealed class AiPlayerSession : IAsyncDisposable
|
||||
|
||||
// ── Action → message mapping ──────────────────────────────────────────────
|
||||
|
||||
/// <summary>
|
||||
/// Maps an AiAction to the game message type and JSON payload.
|
||||
/// Returns (null, null) for actions that don't produce a message (e.g., internal guards).
|
||||
/// </summary>
|
||||
private (string? msgType, ReadOnlyMemory<byte> payload) ActionToMessage(AiAction action)
|
||||
{
|
||||
return action switch
|
||||
@@ -292,10 +373,6 @@ internal sealed class AiPlayerSession : IAsyncDisposable
|
||||
|
||||
// ── Handler invocation ────────────────────────────────────────────────────
|
||||
|
||||
/// <summary>
|
||||
/// Resolves and invokes a game message handler directly in-process,
|
||||
/// as if the AI were a connected client sending that message.
|
||||
/// </summary>
|
||||
private async Task InvokeHandlerAsync(
|
||||
string messageType,
|
||||
ReadOnlyMemory<byte> payload,
|
||||
|
||||
@@ -8,19 +8,17 @@ using Microsoft.Extensions.Hosting;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using SOR.Ai.Tracking;
|
||||
using SOR.Database.Contexts;
|
||||
using SOR.Database.Enums;
|
||||
using SOR.Game;
|
||||
using SOR.Shared.Nats;
|
||||
using SOR.Networking.Abstractions.EventBus;
|
||||
|
||||
/// <summary>
|
||||
/// Singleton BackgroundService that orchestrates AI player turns across all active sessions.
|
||||
/// Singleton BackgroundService that orchestrates AI player sessions across all active games.
|
||||
///
|
||||
/// On startup: subscribes to NATS GameStartedEvent and AiTurnStartedEvent.
|
||||
/// On GameStartedEvent: inspects the session for AI seats and creates AiPlayerSession
|
||||
/// instances, then sends game.ready on behalf of each AI seat.
|
||||
/// On AiTurnStartedEvent: loads the game state and calls AiPlayerSession.ExecuteTurnAsync.
|
||||
/// On GameEndedEvent: disposes AI sessions for that game.
|
||||
/// On startup: subscribes to NATS GameStartedEvent and GameEndedEvent.
|
||||
/// On GameStartedEvent: inspects the session for AI seats, creates AiPlayerSession
|
||||
/// instances, and starts their RunAsync polling loops (which handle ready + all turns).
|
||||
/// On GameEndedEvent: cancels and disposes AI sessions for that game.
|
||||
/// </summary>
|
||||
public sealed class AiPlayerSessionManager : BackgroundService
|
||||
{
|
||||
@@ -48,12 +46,13 @@ public sealed class AiPlayerSessionManager : BackgroundService
|
||||
{
|
||||
_logger.LogInformation("AiPlayerSessionManager started.");
|
||||
|
||||
// Subscribe to all three NATS subjects concurrently.
|
||||
// Subscribe to game lifecycle NATS subjects concurrently.
|
||||
// Turn execution is driven by per-session polling loops (AiPlayerSession.RunAsync),
|
||||
// not by AiTurnStartedEvent — polling is more resilient to missed events.
|
||||
var gameStartedTask = ConsumeGameStartedAsync(stoppingToken);
|
||||
var aiTurnTask = ConsumeAiTurnStartedAsync(stoppingToken);
|
||||
var gameEndedTask = ConsumeGameEndedAsync(stoppingToken);
|
||||
|
||||
await Task.WhenAll(gameStartedTask, aiTurnTask, gameEndedTask);
|
||||
await Task.WhenAll(gameStartedTask, gameEndedTask);
|
||||
|
||||
_logger.LogInformation("AiPlayerSessionManager stopped.");
|
||||
}
|
||||
@@ -77,23 +76,6 @@ public sealed class AiPlayerSessionManager : BackgroundService
|
||||
}
|
||||
}
|
||||
|
||||
private async Task ConsumeAiTurnStartedAsync(CancellationToken ct)
|
||||
{
|
||||
try
|
||||
{
|
||||
await foreach (var evt in _eventBus.SubscribeAsync<AiTurnStartedEvent>(
|
||||
NatsSubjects.AiTurnStarted, ct))
|
||||
{
|
||||
_ = Task.Run(() => OnAiTurnStartedAsync(evt, ct), ct);
|
||||
}
|
||||
}
|
||||
catch (OperationCanceledException) { /* normal shutdown */ }
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "AiPlayerSessionManager: AiTurnStarted consumer crashed.");
|
||||
}
|
||||
}
|
||||
|
||||
private async Task ConsumeGameEndedAsync(CancellationToken ct)
|
||||
{
|
||||
try
|
||||
@@ -220,33 +202,10 @@ public sealed class AiPlayerSessionManager : BackgroundService
|
||||
|
||||
_sessions.TryAdd(session.Id, sessionList);
|
||||
|
||||
// Send game.ready for each AI seat.
|
||||
// Start the polling loop for each AI seat.
|
||||
// RunAsync sends game.ready then polls DB state every ~1 s to drive turns.
|
||||
foreach (var aiSession in sessionList)
|
||||
_ = Task.Run(() => aiSession.SendReadyAsync(ct), ct);
|
||||
}
|
||||
|
||||
private async Task OnAiTurnStartedAsync(AiTurnStartedEvent evt, CancellationToken ct)
|
||||
{
|
||||
if (!_sessions.TryGetValue(evt.SessionId, out var sessionList))
|
||||
return;
|
||||
|
||||
var aiSession = sessionList.FirstOrDefault(s => s.AiAccountId == evt.AiAccountId);
|
||||
if (aiSession is null)
|
||||
return;
|
||||
|
||||
// Load current game state from the DB.
|
||||
await using var scope = _scopeFactory.CreateAsyncScope();
|
||||
var gameDb = scope.ServiceProvider.GetRequiredService<GameDbContext>();
|
||||
|
||||
var session = await gameDb.GameSessions
|
||||
.AsNoTracking()
|
||||
.FirstOrDefaultAsync(s => s.Id == evt.SessionId, ct);
|
||||
|
||||
if (session is null || session.Status != GameSessionStatus.Active || session.StateJson is null)
|
||||
return;
|
||||
|
||||
var state = GameEngine.Deserialize(session.StateJson);
|
||||
await aiSession.ExecuteTurnAsync(state, ct);
|
||||
_ = Task.Run(() => aiSession.RunAsync(ct), ct);
|
||||
}
|
||||
|
||||
private void OnGameEnded(Guid sessionId)
|
||||
|
||||
Reference in New Issue
Block a user