Files
VoiceStudio/backend/core/activity.py
Palash Debnath d6bd82844c Restart a crashed engine, ask before quitting running work, keep the batch queue across restarts (#4623)
* feat(desktop): restart a crashed engine, ask before quitting running work, keep the batch queue across restarts

- A local engine that crashed after it had started restarts on its own
  (1, 3, 6, 12, 30 s); a sixth crash in ten minutes, or a crash before it
  ever started, stays on the recovery screen.
- A quit the user starts asks first while the engine reports running work;
  confirmed update installs, OS shutdown and relaunches do not ask.
- Unfinished batch jobs keep a record beside their upload and are queued
  again, in order, on the next backend start.
- Interrupted audiobook/story renders are announced once after launch with
  a Resume action.

* changelog: add fragment for #4623

* test(dub): wait for the voice search to take focus

* fix(desktop): close the gaps review found in job resume and the quit prompt

- Quitting during a generation, clone, design or transcription now asks
  first: the engine reports open requests that do work, not just jobs.
- Restart on CPU withdraws a pending automatic restart before it saves the
  device choice, so the engine cannot start on the old device.
- Batch queue records hold only the upload's name, so they carry no home
  path and still restore after the data folder moves.
- A save racing a cancel, a job skipped as cancelled, or a record that
  cannot be deleted no longer brings finished or cancelled work back.
- One malformed record is dropped on its own instead of stopping every
  saved job from restoring.
- A queued or restored job whose speech model was removed fails with the
  enqueue message instead of downloading it.
- The interrupted-render notice retries a failed check a few times.
2026-12-04 03:43:28 +05:30

103 lines
3.4 KiB
Python

"""Report whether this backend is doing work, for idle shutdown by its owner.
The desktop app stops a backend it started for a terminal command once the
backend has been idle for a while. "Idle" must be conservative: a dub, a batch,
a model download or an open stream all keep it alive. Requests and WebSocket
sessions are counted by middleware; long-running work that outlives its request
registers a probe from the module that owns the work, so this module never
imports engine code and new job types extend the rule where they are defined.
"""
from __future__ import annotations
import logging
import threading
import time
from typing import Callable
from starlette.types import ASGIApp, Receive, Scope, Send
logger = logging.getLogger("omnivoice.activity")
# Polls of these paths are how owners observe the backend; they are not use.
_PASSIVE_PATHS = frozenset({"/health", "/startup/progress", "/system/activity", "/system/api-activity"})
_lock = threading.Lock()
_inflight = 0
# Open HTTP requests that change something (a generation, a transcription, a
# render stream): unlike reads and WebSocket sessions, quitting would cut them.
_work_requests = 0
# Reads change nothing, so quitting mid-read loses nothing.
_READ_METHODS = frozenset({"GET", "HEAD", "OPTIONS"})
_last_activity = time.monotonic()
_probes: dict[str, Callable[[], bool]] = {}
def register_probe(name: str, probe: Callable[[], bool]) -> None:
"""Register ``probe() -> True`` while work named ``name`` is running."""
with _lock:
_probes[name] = probe
def touch() -> None:
global _last_activity
with _lock:
_last_activity = time.monotonic()
def _enter(work: bool = False) -> None:
global _inflight, _work_requests, _last_activity
with _lock:
_inflight += 1
_work_requests += work
_last_activity = time.monotonic()
def _leave(work: bool = False) -> None:
global _inflight, _work_requests, _last_activity
with _lock:
_inflight -= 1
_work_requests -= work
_last_activity = time.monotonic()
def snapshot() -> dict:
with _lock:
inflight = _inflight
work_requests = _work_requests
idle = time.monotonic() - _last_activity
probes = list(_probes.items())
busy = []
for name, probe in probes:
try:
if probe():
busy.append(name)
except Exception:
# An unreadable registry must keep the backend alive, never stop it.
logger.debug("activity probe %s failed", name, exc_info=True)
busy.append(name)
if inflight or busy:
idle = 0.0
return {
"inflight": inflight,
"work_requests": work_requests,
"busy": sorted(busy),
"idle_seconds": round(idle, 1),
}
class ActivityMiddleware:
"""Count open HTTP requests (including streams) and WebSocket sessions."""
def __init__(self, app: ASGIApp) -> None:
self.app = app
async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None:
if scope["type"] not in {"http", "websocket"} or scope.get("path") in _PASSIVE_PATHS:
await self.app(scope, receive, send)
return
work = scope["type"] == "http" and scope.get("method", "GET") not in _READ_METHODS
_enter(work)
try:
await self.app(scope, receive, send)
finally:
_leave(work)