feat(app): performance stages move the LLM between the normal and the game placement

- while the services run, game mode decides the stage (perf.rs): a game means the game stage at
  once (or pause with game.pauseInGame); its end brings the normal stage back after
  game.revertSeconds (default 30)
- a change tells the voice worker the LLM switches (llm switching, with a notice), waits until
  the brain has written the answers in progress (llm_idle, at most 2 minutes), restarts the LLM in
  the stage and tells the worker it is ready or paused
- the game stage runs at 16K context, one request at a time, half the engine's CPU threads and
  the game placement (reserve game.reserveGb, default 8, else 2 GiB, else 0 GiB, else pause),
  measured once at that context; every placement of a run counts other programs' memory as it
  was when the services started
- the voice worker gates every LLM use: on switching new work waits (at most 180 s), the first
  spoken request that waits hears the notice once under its own id, on ready all go on, on
  paused nothing is answered
- dashboard: "성능 단계: 게임 중 · 게임에 X GB" / 일시정지; game mode screen: game VRAM, revert
  wait, pause in game

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
javis-bot
2026-11-14 10:23:21 +09:00
parent b6bd1be6fb
commit 7e096b449e
18 changed files with 746 additions and 68 deletions

View File

@@ -3,6 +3,7 @@
from __future__ import annotations
import asyncio
import contextlib
import hmac
import ipaddress
import itertools
@@ -38,6 +39,15 @@ def is_loopback(host: str) -> bool:
return False
# How long a request waits for the LLM to come back from a switch (a restart takes 30-50 s; the
# first game switch also measures once).
LLM_WAIT_S = 180.0
class _LlmPaused(Exception):
"""The app paused the LLM (a game runs): nothing is answered until it is ready again."""
class VoiceWorker:
def __init__(self, token: str, transcriber: Transcriber | None, vad_factory: Callable[[], VadStream],
tts_engine: TtsEngine | None = None, hello_timeout_s: float = 5.0, tick_s: float = 0.05,
@@ -59,6 +69,16 @@ class VoiceWorker:
# memory and delete confirmations ("the very next message") follow the order they asked.
self.brain_lanes = {"voice": asyncio.Lock(), "chat": asyncio.Lock()}
self.brain_people: dict[str, asyncio.Lock] = {}
# The LLM's state from the app (voice_worker.spec.md, "LLM switches"): while it switches or
# is paused no new brain work starts; the brain work running when a switch is announced
# finishes first, then the app is told the brain is idle.
self.llm_state = "ready"
self.llm_ready = asyncio.Event()
self.llm_ready.set()
self.llm_notice: str | None = None
self.llm_noticed = False
self.llm_active = 0
self.llm_idle_to = None # the session to tell once nothing runs
self.chat_timeout_s = chat_timeout_s
self.delivery_timeout_s = delivery_timeout_s # a chat answer the app never reports: not posted
# chat_action ids are unique across connections and worker runs, so a late answer from an
@@ -320,7 +340,7 @@ class Session:
"addressed": self._on_addressed, "rank": self._on_rank,
"chat_channels": self._on_chat_channels, "chat_action_result": self._on_chat_action_result,
"memory_config": self._on_memory_config, "reply_delivered": self._on_reply_delivered,
"prepare": self._on_prepare}.get(kind)
"prepare": self._on_prepare, "llm": self._on_llm}.get(kind)
if handler is None:
self.error("bad_message", f"unknown type: {kind!r}")
return
@@ -519,6 +539,56 @@ class Session:
waiting[user] = waiting.get(user, 0) + 1
asyncio.get_running_loop().create_task(self._reply(rid, user, text, via, speak, early))
def _on_llm(self, msg: dict) -> None:
state, notice = msg.get("state"), msg.get("notice")
if state not in ("switching", "ready", "paused") or not (notice is None or isinstance(notice, str)):
self.error("bad_message", "llm needs state switching|ready|paused and an optional string notice")
return
w = self.worker
w.llm_state = state
debug_log(f"llm {state}", "llm")
if state == "ready":
w.llm_notice, w.llm_idle_to = None, None
w.llm_ready.set()
return
w.llm_ready.clear()
if state == "switching":
w.llm_notice, w.llm_noticed = notice or None, False
w.llm_idle_to = self
self._llm_check_idle()
else:
w.llm_ready.set() # paused: waiting requests stop waiting and answer nothing
def _llm_check_idle(self) -> None:
w = self.worker
if w.llm_state == "switching" and w.llm_active == 0 and w.llm_idle_to is not None:
to, w.llm_idle_to = w.llm_idle_to, None
to.send({"type": "llm_idle"})
@contextlib.asynccontextmanager
async def _llm(self, notice_id: str | None = None):
"""Brain work that uses the LLM: it waits while the LLM switches (the first spoken request
that waits hears the notice once, under its own id), fails while paused, and counts as
running so a switch waits for it."""
w = self.worker
while w.llm_state != "ready":
if w.llm_state == "paused":
raise _LlmPaused()
if notice_id and w.llm_notice and not w.llm_noticed:
w.llm_noticed = True
# The newline ends it as a sentence, so it is spoken now, not joined to the answer.
self._on_tts({"type": "tts", "id": notice_id, "text": w.llm_notice + "\n", "more": True})
try:
await asyncio.wait_for(w.llm_ready.wait(), LLM_WAIT_S)
except asyncio.TimeoutError:
break # go on: the call fails on its own if the LLM is still away
w.llm_active += 1
try:
yield
finally:
w.llm_active -= 1
self._llm_check_idle()
def _on_prepare(self, msg: dict) -> None:
"""A call still being said: the brain gets ready for it. One prepare per user runs at a time;
while it runs only the newest text waits, and one about the same as the last one prepared
@@ -544,7 +614,8 @@ class Session:
while text is not None and not self.closed:
self.last_prepared[user] = text
try:
await asyncio.to_thread(self.worker.brain.prepare, user, text, bool(self.chat_channels))
async with self._llm():
await asyncio.to_thread(self.worker.brain.prepare, user, text, bool(self.chat_channels))
except Exception as e: # the brain must never take the session down
debug_log(f"brain prepare failed: {type(e).__name__}", "llm")
newer, self.preparing[user] = self.preparing[user], None
@@ -563,7 +634,8 @@ class Session:
async def judge():
try:
yes = await asyncio.to_thread(self.worker.brain.addressed, user, text, list(self.settings.hotwords))
async with self._llm():
yes = await asyncio.to_thread(self.worker.brain.addressed, user, text, list(self.settings.hotwords))
except Exception as e: # the brain must never take the session down
debug_log(f"brain addressed {qid} failed: {type(e).__name__}", "llm")
yes = None
@@ -585,7 +657,8 @@ class Session:
async def rank():
try:
order = await asyncio.to_thread(self.worker.brain.rank, cands)
async with self._llm():
order = await asyncio.to_thread(self.worker.brain.rank, cands)
except Exception as e:
debug_log(f"brain rank {qid} failed: {type(e).__name__}", "llm")
order = None
@@ -658,11 +731,14 @@ class Session:
chat = ChatBridge(self, asyncio.get_running_loop(), turn, w.pending_deletes.setdefault(user, {})) \
if self.chat_channels else None
try:
answer = await asyncio.to_thread(w.brain.reply, user, text, history, chat=chat)
async with self._llm(rid if speak else None):
answer = await asyncio.to_thread(w.brain.reply, user, text, history, chat=chat)
except Exception as e: # the brain must never take the session down
debug_log(f"brain reply {rid} failed: {type(e).__name__}", "llm")
answer = None
answer = (answer or "").strip()
if not answer and rid in self.tts_requests:
self._on_tts({"type": "tts", "id": rid, "text": "", "more": False}) # ends the notice's speech
self.send({"type": "reply_text", "id": rid, "text": answer, "failed": not answer})
# The answer reaches them when spoken (tts_done) or when the app reports the post
# (reply_delivered); an unspoken voice answer has nothing more to wait for.