StockAnalysis / services /test_simulation.py
igardner's picture
fix: reset corrupt sqlite and reduce lobby load
626842d
Raw History Blame Contribute Delete
10.7 kB
"""Opt-in simulated guests for exercising automatic matchmaking end to end."""
from __future__ import annotations
import json
import logging
import random
import time
from config import Config
from extensions import db
from games import registry
from models import Game, GamePlayer, MatchmakingEntry, Room, RoomMembership, User, ChatMessage
from services.avatar import AvatarService
from services.connections import MANAGER
from services.lobby import LOBBY_PROMPTS, create_lobby_message, join_queue
from services.test_players import TestMode
logger = logging.getLogger(__name__)
BOT_RESPONSES = (
"I watch who answers before anyone else.",
"I pretend I did not hear the question.",
"The quietest person is rarely the least observant.",
"I say what the room expects, then watch who believes me.",
)
class TestSimulation:
"""Drive one shared waiting room and stable bot accounts in TEST_MODE.
Bots are queued only in response to at least one real waiting guest. They
never create bot-only rooms. Their user rows are reused across messages so
chat attribution stays stable.
"""
def __init__(self):
self.bot_ids: list[int] = []
self.late_bot_at: float | None = None
self.last_lobby_chatter = 0.0
self.last_room_chatter: dict[int, float] = {}
self.lobby_chatter_index = 0
self.room_chatter_index: dict[int, int] = {}
def initialize(self):
self.bot_ids = [
user.id
for user in TestMode.ensure_test_players(Config.TEST_BOT_MAX_ACCOUNTS)
]
logger.info("TEST_SIMULATION_READY bots=%s", self.bot_ids)
def tick(self):
if not Config.TEST_MODE:
return
if not self.bot_ids:
self.initialize()
now = time.monotonic()
real_queued = self._real_queue_count()
if not real_queued:
self._pause_waiting_bots()
self.late_bot_at = None
else:
self._fill_queue(real_queued, now)
self._lobby_chatter(real_queued, now)
self._room_chatter(now)
self._play_games(now)
@staticmethod
def _real_queue_count():
return (MatchmakingEntry.query.join(User, User.id == MatchmakingEntry.user_id)
.filter(MatchmakingEntry.status == "queued", User.is_test_bot.is_(False))
.count())
def _bot_queue_entries(self):
return (MatchmakingEntry.query.join(User, User.id == MatchmakingEntry.user_id)
.filter(MatchmakingEntry.status == "queued", User.is_test_bot.is_(True))
.order_by(MatchmakingEntry.joined_at.asc()).all())
def _available_bots(self, needed=0):
active_games = {
user_id for (user_id,) in db.session.query(GamePlayer.user_id)
.join(Game, Game.id == GamePlayer.game_id)
.join(User, User.id == GamePlayer.user_id)
.filter(Game.ended_at.is_(None), User.is_test_bot.is_(True)).all()
}
active_rooms = {
user_id for (user_id,) in db.session.query(RoomMembership.user_id)
.join(Room, Room.id == RoomMembership.room_id)
.join(User, User.id == RoomMembership.user_id)
.filter(Room.status == "lobby", RoomMembership.left_at.is_(None), User.is_test_bot.is_(True)).all()
}
queued = {entry.user_id for entry in self._bot_queue_entries()}
available = [
user for user in TestMode.test_players()
if user.id not in active_games | active_rooms | queued
]
return available
def _queue_bot(self, bot: User):
entry = join_queue(bot.id)
prompt = next((item for item in LOBBY_PROMPTS if item["id"] == entry.participation_prompt_id), None)
prompt = prompt or {"prompt": "What do you notice about this room?"}
answer = BOT_RESPONSES[(bot.id - 1) % len(BOT_RESPONSES)]
logger.info("TEST_BOT_QUEUE user=%s prompt=%s", bot.id, prompt["prompt"])
create_lobby_message(answer, user_id=bot.id, source="simulation")
def _fill_queue(self, real_count: int, now: float):
needed = max(0, min(4, Config.MATCHMAKING_MIN_PLAYERS - real_count))
entries = self._bot_queue_entries()
# Keep the pool sized to the real guests; unused simulated entries wait
# in a paused state instead of tipping a different table into a match.
target_now = min(3, needed)
excess = entries[target_now:]
for entry in excess:
entry.status = "paused"
entry.participated_at = None
if excess:
db.session.commit()
existing_ids = {entry.user_id for entry in entries[:target_now]}
available = self._available_bots(max(0, target_now - len(existing_ids)))
for bot in available:
if len(existing_ids) >= target_now:
break
if bot.id in existing_ids:
continue
self._queue_bot(bot)
existing_ids.add(bot.id)
current_count = len(self._bot_queue_entries())
if needed > current_count and needed > target_now:
if self.late_bot_at is None:
self.late_bot_at = now + 4.0
logger.info("TEST_LATE_GUEST_SCHEDULED delay=4s real_waiters=%s", real_count)
elif now >= self.late_bot_at:
queued_ids = {entry.user_id for entry in self._bot_queue_entries()}
available = self._available_bots(max(0, needed - len(queued_ids)))
for bot in available:
if len(queued_ids) >= needed:
break
if bot.id in queued_ids:
continue
self._queue_bot(bot)
queued_ids.add(bot.id)
self.late_bot_at = None
else:
self.late_bot_at = None
def _pause_waiting_bots(self):
entries = self._bot_queue_entries()
if not entries:
return
for entry in entries:
entry.status = "paused"
entry.participated_at = None
db.session.commit()
logger.info("TEST_BOT_QUEUE_PAUSED bots=%s", len(entries))
def _lobby_chatter(self, real_count: int, now: float):
if now - self.last_lobby_chatter < Config.TEST_BOT_CHAT_INTERVAL:
return
self.last_lobby_chatter = now
bots = [db.session.get(User, entry.user_id) for entry in self._bot_queue_entries()]
bots = [bot for bot in bots if bot]
if bots:
bot = bots[self.lobby_chatter_index % len(bots)]
self.lobby_chatter_index += 1
create_lobby_message("DURRRR", user_id=bot.id, source="simulation")
def _room_chatter(self, now: float):
games = Game.query.filter(Game.ended_at.is_(None)).all()
for game in games:
if now - self.last_room_chatter.get(game.id, 0.0) < Config.TEST_BOT_CHAT_INTERVAL:
continue
bot_players = (GamePlayer.query.filter_by(game_id=game.id, alive=True)
.join(User, User.id == GamePlayer.user_id)
.filter(User.is_test_bot.is_(True)).all())
if not bot_players:
continue
self.last_room_chatter[game.id] = now
index = self.room_chatter_index.get(game.id, 0) % len(bot_players)
player = bot_players[index]
self.room_chatter_index[game.id] = index + 1
user = db.session.get(User, player.user_id)
if not user:
continue
message = ChatMessage(room_id=game.room_id, user_id=user.id, content="DURRRR")
db.session.add(message)
db.session.flush()
MANAGER.broadcast(game.room_id, json.dumps({
"type": "chat",
"id": message.id,
"user": user.nickname,
"msg": message.content,
"at": message.created_at.strftime("%H:%M") if message.created_at else "",
"avatar": AvatarService.build_url(user.avatar_style, user.avatar_seed, user.avatar_bg),
"is_simulated": True,
}))
logger.info("[BOT_CHAT] room=%s user_id=%s nickname=%s message=%s", game.room_id, user.id, user.nickname, message.content)
db.session.commit()
def _play_games(self, now: float):
from services.gameplay import perform_action
for game in Game.query.filter(Game.ended_at.is_(None)).all():
game_class = registry.get(game.game_type)
if not game_class or game.game_type != "parlor_mystery":
continue
try:
state = json.loads(game.state_json or "{}")
except ValueError:
logger.exception("TEST_GAME_STATE_INVALID game=%s", game.id)
continue
alive = [int(user_id) for user_id in state.get("alive", [])]
role_map = state.get("role_by_player", {})
bots = [player.user_id for player in GamePlayer.query.filter_by(game_id=game.id, alive=True)
.join(User, User.id == GamePlayer.user_id).filter(User.is_test_bot.is_(True)).all()
if player.user_id in alive]
if not bots:
continue
elapsed = now - float(state.get("phase_started_at", now))
try:
if state.get("phase") == "discussion" and elapsed >= 18:
perform_action(game.room_id, bots[0], "begin_vote", {})
elif state.get("phase") == "vote":
for bot_id in bots:
current = Game.query.get(game.id)
latest = json.loads(current.state_json or "{}")
if latest.get("phase") != "vote" or str(bot_id) in latest.get("votes", {}):
continue
candidates = [user_id for user_id in alive if user_id != bot_id]
if not candidates:
continue
target = random.Random(f"{game.id}:{latest.get('round')}:{bot_id}").choice(candidates)
perform_action(game.room_id, bot_id, "vote", {"target_user_id": target})
elif state.get("phase") == "reveal" and elapsed >= 14:
perform_action(game.room_id, bots[0], "continue", {})
except (LookupError, PermissionError, ValueError):
# Another guest action may have advanced the phase between the
# simulation snapshot and its action; reload on the next tick.
continue
SIMULATION = TestSimulation()