"""Model installation invariants without network or real model downloads.""" from __future__ import annotations import hashlib import threading from unittest.mock import AsyncMock, MagicMock import httpx import pytest from voice_dictation.core import model_manager as module from voice_dictation.core.model_manager import ( DownloadCancelled, ModelError, ModelManager, ModelSpec, ) @pytest.fixture def fixture_model(monkeypatch): content = b"small synthetic model bytes" spec = ModelSpec( "test", "Test", "https://example.invalid/model", len(content), hashlib.sha256(content).hexdigest(), ) monkeypatch.setattr(module, "CATALOG", (spec,)) response = MagicMock() response.blocks = [content[:8], content[8:]] async def chunks(): for block in response.blocks: yield block response.aiter_bytes = chunks stream = MagicMock() stream.__aenter__ = AsyncMock(return_value=response) stream.__aexit__ = AsyncMock(return_value=False) client = MagicMock() client.stream.return_value = stream client.__aenter__ = AsyncMock(return_value=client) client.__aexit__ = AsyncMock(return_value=False) monkeypatch.setattr(module.httpx, "AsyncClient", lambda *a, **kw: client) return spec, content, response def test_verified_atomic_download(tmp_path, fixture_model): spec, content, _ = fixture_model manager = ModelManager(tmp_path) progress = [] path = manager.download(spec.id, lambda done, total: progress.append((done, total))) assert path.read_bytes() == content assert manager.is_installed(spec.id) assert progress[-1] == (len(content), len(content)) assert not list(tmp_path.glob("*.part")) manager.delete(spec.id) assert not manager.is_installed(spec.id) def test_corrupt_download_never_installed(tmp_path, fixture_model): spec, _, response = fixture_model response.blocks = [b"corrupt"] manager = ModelManager(tmp_path) with pytest.raises(ModelError, match="SHA256"): manager.download(spec.id) assert not manager.is_installed(spec.id) assert not list(tmp_path.glob("*.part")) def test_cancel_removes_partial(tmp_path, fixture_model): spec, _, _ = fixture_model cancel = threading.Event() manager = ModelManager(tmp_path) with pytest.raises(DownloadCancelled): manager.download(spec.id, lambda *_: cancel.set(), cancel) assert not manager.path_for(spec.id).exists() assert not list(tmp_path.glob("*.part")) def test_concurrent_download_and_delete_rejected(tmp_path, fixture_model): spec, _, _ = fixture_model manager = ModelManager(tmp_path) with manager._lock(spec.id): with pytest.raises(ModelError, match="другом окне"): ModelManager(tmp_path).download(spec.id) with pytest.raises(ModelError, match="другом окне"): ModelManager(tmp_path).delete(spec.id) def test_network_failure_preserves_old_model(tmp_path, fixture_model): spec, content, response = fixture_model manager = ModelManager(tmp_path) path = manager.path_for(spec.id) path.write_bytes(b"previous corrupt model") response.raise_for_status.side_effect = httpx.ConnectError("failed") with pytest.raises(ModelError): manager.download(spec.id) assert path.read_bytes() == b"previous corrupt model" assert not list(tmp_path.glob("*.part")) path.write_bytes(content) assert manager.download(spec.id) == path @pytest.mark.parametrize("model_id", ["../escape", "/tmp/escape", "unknown", "test/../../escape"]) def test_unknown_ids_rejected(tmp_path, fixture_model, model_id): with pytest.raises(ModelError): ModelManager(tmp_path).download(model_id) def test_symlink_rejected(tmp_path, fixture_model): target = tmp_path / "target" target.write_bytes(b"keep") (tmp_path / "test.bin").symlink_to(target) with pytest.raises(ModelError, match="ссылкой"): ModelManager(tmp_path).delete("test") assert target.read_bytes() == b"keep" def test_inference_lease_blocks_delete_and_releases(tmp_path, fixture_model): spec, content, _ = fixture_model manager = ModelManager(tmp_path) manager.path_for(spec.id).write_bytes(content) with manager.use(spec.id) as path: assert path.read_bytes() == content with pytest.raises(ModelError, match="другом окне"): ModelManager(tmp_path).delete(spec.id) manager.delete(spec.id) assert not manager.is_installed(spec.id) @pytest.mark.parametrize("oversize", [False, True]) def test_wrong_hash_and_oversize_rejected(tmp_path, fixture_model, oversize): spec, content, response = fixture_model response.blocks = [b"x" * (len(content) + int(oversize))] manager = ModelManager(tmp_path) with pytest.raises(ModelError): manager.download(spec.id) assert not manager.path_for(spec.id).exists() assert not list(tmp_path.glob("*.part")) def test_precancelled_download_makes_no_request(tmp_path, fixture_model, monkeypatch): spec, _, _ = fixture_model request = MagicMock() monkeypatch.setattr(module.httpx, "AsyncClient", request) cancel = threading.Event() cancel.set() with pytest.raises(DownloadCancelled): ModelManager(tmp_path).download(spec.id, cancel=cancel) request.assert_not_called() def test_partial_symlink_cannot_overwrite_target(tmp_path, fixture_model): spec, _, _ = fixture_model target = tmp_path / "target" target.write_bytes(b"keep") (tmp_path / "test.bin.part").symlink_to(target) with pytest.raises(ModelError, match="ссылкой"): ModelManager(tmp_path).download(spec.id) assert target.read_bytes() == b"keep" @pytest.mark.parametrize("blocked_stage", ["connecting", "downloading"]) def test_cancel_interrupts_blocked_socket_and_finishes_cleanup( tmp_path, fixture_model, monkeypatch, blocked_stage ): import asyncio import time spec, _, response = fixture_model entered = threading.Event() cleaned = threading.Event() cancel = threading.Event() class BlockedStream: async def __aenter__(self): if blocked_stage == "connecting": entered.set() try: await asyncio.sleep(60) finally: cleaned.set() return response async def __aexit__(self, *args): cleaned.set() async def slow_bytes(): entered.set() await asyncio.sleep(60) yield b"never delivered" response.aiter_bytes = slow_bytes client = MagicMock() client.stream.return_value = BlockedStream() client.__aenter__ = AsyncMock(return_value=client) client.__aexit__ = AsyncMock(return_value=False) monkeypatch.setattr(module.httpx, "AsyncClient", lambda **kwargs: client) def trigger_cancel(): assert entered.wait(2) cancel.set() trigger = threading.Thread(target=trigger_cancel) trigger.start() started = time.monotonic() with pytest.raises(DownloadCancelled): ModelManager(tmp_path).download(spec.id, cancel=cancel) elapsed = time.monotonic() - started trigger.join(2) assert elapsed < 1.0 assert cleaned.is_set() assert not list(tmp_path.glob("*.part")) assert not ModelManager(tmp_path).path_for(spec.id).exists() client.__aexit__.assert_awaited_once() # Lock release proves no downloader continues owning the operation. with ModelManager(tmp_path)._lock(spec.id): pass def test_stage_order_and_safe_operation_logs(tmp_path, fixture_model, caplog): import logging spec, _, _ = fixture_model stages = [] with caplog.at_level(logging.INFO, logger=module.__name__): ModelManager(tmp_path).download(spec.id, stage=stages.append) assert stages == ["checking", "connecting", "downloading", "verifying"] assert "model.download.started" in caplog.text assert "model.download.completed" in caplog.text assert "operation=" in caplog.text assert spec.url not in caplog.text def test_failure_log_does_not_expose_network_exception(tmp_path, fixture_model, caplog): spec, _, response = fixture_model response.raise_for_status.side_effect = httpx.ConnectError("SECRET SIGNED URL") with pytest.raises(ModelError): ModelManager(tmp_path).download(spec.id) assert "model.download.failed" in caplog.text assert "SECRET" not in caplog.text