File size: 10,745 Bytes
626842d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
"""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()