Files
VoiceStudio/tests/test_engine_availability_real_import.py
Palash Debnath 1f658f844e perf: speed up Electron startup, UI responsiveness, and backend DB/engine boot (#4320)
* perf: speed up Electron startup, UI rendering, and backend engine/DB boot

* chore: add changelog fragment for #4320

* perf: add SQLite indexes/pragmas, selective gzip, and immutable asset cache

* fix: restore the omnivoice-gallery pin to main's commit

The branch moved the submodule pointer back to 22e8e6da8, failing the
forward-only pin check.

* fix(db): create perf indexes after the additive reconcile so legacy DBs upgrade

The history/list sort indexes sat in _BASE_SCHEMA, so a legacy generation_history
without 'starred' aborted init_db's executescript with 'no such column: starred'
before _migrate could add it. Move them to _ensure_perf_indexes(), run after
_reconcile_additive_columns, skipping any index whose table/columns are absent.

* fix(electron): load the voices sidebar eagerly so it precedes page content

Lazy-loading VoicesSidebar made it mount after the page, so on first paint the
clone page's full-card voice button was the first 'Language fixture' button and
a click on it landed on the profile photo label (language-picker-smoke timeout).
It also made the sidebar pop in late. Restore the eager import.

* test(openai): drop the wire encoding when the SDK transport replays a decoded body

TestClient already decompresses res.content, so replaying it with the gzip
Content-Encoding header made httpx decode twice (incorrect header check) once
/v1/models was compressed. Add a wire-level check that the compressed body is valid.

* test(moss): resolve the lazy transformers __version__ before rebinding the module

transformers is a lazy module whose __version__ only enters its __dict__ once read;
the rebound copy lacked it when nothing had read it yet.

* fix(electron): serve app:// static files from a single open handle

Stat then read let the file change in between (CodeQL js/file-system-race). One
FileHandle now provides the stat, the read and the stream, and the content-length
of a buffered file comes from the bytes actually read.

* feat(db): add alembic revision 0019 for the list sort indexes

Schema changes go through alembic with a tested upgrade path. The revision creates
the seven indexes IF NOT EXISTS, only where the table and columns exist; init_db's
_ensure_perf_indexes stays for installs where alembic cannot run, and a test keeps
the two lists equal. Also make the alembic fast-path test fail if alembic is imported.

* fix(api): skip gzip for all media mounts and honour Accept-Encoding q-values

/voice_audio and /demo_audio were compressed on the event loop, and gzip;q=0 was
answered with gzip because Starlette matches the substring. Parse the header per
RFC 9110 before delegating, and require compression in the /v1/models wire test.

* fix(electron): start the backend after agent discovery, defer the dock, harden the palette

- Spawn Python only once registerRepairAgents set VOICESTUDIO_LLM_AGENTS; window,
  tray and updater still overlap with it.
- RepairAgentDock mounted at startup because Boolean(state) is always true; test runs.
- Command palette: LazyBoundary closes on a failed chunk, Escape works while the
  chunk loads, the highlight follows the command id, and loading/error are not
  reported as no matches.
- Tighten the app:// handle test to swap the path after the stat.

* fix(engines): report omnivoice and kittentts ready only when they really import

#4320 replaced their import check with a package-spec lookup, so an installed
package with a missing dependency or broken native library showed as ready on
/engines and /engines/{id}/health. Restore the real import (it is cached in
sys.modules after the first success); the parallel probing is kept. No other
backend used the spec-only pattern.

* fix(engines): probe engine availability serially again

The thread-pool probing in list_backends (tts and asr) and /engines raced the
first imports of heavy, interdependent packages, so the active engine could be
reported unavailable. Restore main's serial loops and pin it with a test.
2026-11-21 18:32:31 +05:30

56 lines
2.2 KiB
Python

"""An engine whose package is installed but cannot be imported (missing
dependency, broken native library) must not report ready. #4320 briefly checked
only that the package spec existed, so /engines and /engines/{id}/health said
"ready" for engines that would fail on first use."""
import sys
import pytest
from services.tts_backend import KittenTTSBackend, OmniVoiceBackend
def _purge(prefix):
for name in [n for n in sys.modules if n == prefix or n.startswith(prefix + ".")]:
del sys.modules[name]
@pytest.fixture()
def broken_packages(tmp_path, monkeypatch):
(tmp_path / "kittentts").mkdir()
(tmp_path / "kittentts" / "__init__.py").write_text("import libmissing_native_dep\n")
models = tmp_path / "omnivoice" / "models"
models.mkdir(parents=True)
(tmp_path / "omnivoice" / "__init__.py").write_text("")
(models / "__init__.py").write_text("")
(models / "omnivoice.py").write_text("raise OSError('libcudnn.so.9: cannot open shared object file')\n")
saved = dict(sys.modules)
monkeypatch.syspath_prepend(str(tmp_path))
_purge("kittentts")
_purge("omnivoice")
yield
# Drop the fake packages and put back exactly what was loaded before.
_purge("kittentts")
_purge("omnivoice")
sys.modules.update({n: m for n, m in saved.items() if n.split(".")[0] in ("kittentts", "omnivoice")})
@pytest.mark.parametrize(
("backend", "hint"),
[(KittenTTSBackend, "libmissing_native_dep"), (OmniVoiceBackend, "libcudnn")],
)
def test_present_but_unimportable_package_is_not_ready(broken_packages, backend, hint):
ok, message = backend.is_available()
assert ok is False
assert hint in message # names the actual cause, so the user can act on it
@pytest.mark.parametrize("engine_id", ["kittentts"]) # omnivoice resolves to its sidecar class
def test_health_endpoint_reports_not_ready_for_unimportable_package(broken_packages, engine_id):
from api.routers.engines import _resolve_engine_class, engine_health
if _resolve_engine_class(engine_id) is None:
pytest.skip(f"{engine_id} is not a registered engine id in this build")
result = engine_health(engine_id)
assert result["ok"] is False
assert result["message"]