Make model download cancellation responsive and show operation progress

This commit is contained in:
Vickenty Zherebov 2026-10-19 20:44:54 +03:00
parent 4229605fd5
commit 74d3c87753
4 changed files with 333 additions and 58 deletions

View file

@ -2,18 +2,24 @@
from __future__ import annotations from __future__ import annotations
import asyncio
import hashlib import hashlib
import logging
import shutil import shutil
import sys import sys
import threading import threading
import time
from collections.abc import Callable, Iterator from collections.abc import Callable, Iterator
from contextlib import contextmanager from contextlib import contextmanager, suppress
from dataclasses import dataclass from dataclasses import dataclass
from pathlib import Path from pathlib import Path
from typing import BinaryIO from typing import BinaryIO
from uuid import uuid4
import httpx import httpx
logger = logging.getLogger(__name__)
class ModelError(RuntimeError): class ModelError(RuntimeError):
"""A model operation failed safely.""" """A model operation failed safely."""
@ -161,16 +167,38 @@ class ModelManager:
model_id: str, model_id: str,
progress: Callable[[int, int], None] | None = None, progress: Callable[[int, int], None] | None = None,
cancel: threading.Event | None = None, cancel: threading.Event | None = None,
stage: Callable[[str], None] | None = None,
) -> Path: ) -> Path:
"""Download on explicit request, verify fully, then atomically publish. """Download on explicit request, verify fully, then atomically publish.
A cancelled/failed download removes only its own partial file. Existing A cancelled/failed download removes only its own partial file. Existing
installed models remain untouched. OS locks release even after a crash. installed models remain untouched. OS locks release even after a crash.
``stage`` receives checking, connecting, downloading and verifying. The
synchronous API is intended for a worker thread, not an active asyncio loop.
""" """
spec = self._spec(model_id) spec = self._spec(model_id)
operation = uuid4().hex[:12]
started = time.monotonic()
def notify(value: str) -> None:
logger.info(
"model.download.stage operation=%s model=%s stage=%s", operation, spec.id, value
)
if stage is not None:
stage(value)
def check_cancel() -> None:
if cancel is not None and cancel.is_set():
raise DownloadCancelled("Скачивание отменено")
logger.info("model.download.started operation=%s model=%s", operation, spec.id)
try:
path = self.path_for(model_id) path = self.path_for(model_id)
with self._lock(model_id): with self._lock(model_id):
if self.is_installed(model_id): check_cancel()
notify("checking")
if self._valid_cancellable(path, spec, check_cancel):
logger.info("model.download.cached operation=%s model=%s", operation, spec.id)
return path return path
if shutil.disk_usage(self.models_dir).free < spec.size + 16 * 1024 * 1024: if shutil.disk_usage(self.models_dir).free < spec.size + 16 * 1024 * 1024:
raise ModelError("Недостаточно свободного места для скачивания модели") raise ModelError("Недостаточно свободного места для скачивания модели")
@ -178,37 +206,120 @@ class ModelManager:
if partial.is_symlink(): if partial.is_symlink():
raise ModelError("Временный путь модели не должен быть символической ссылкой") raise ModelError("Временный путь модели не должен быть символической ссылкой")
try: try:
received = 0 loop = asyncio.new_event_loop()
digest = hashlib.sha256() try:
if cancel is not None and cancel.is_set(): loop.run_until_complete(
raise DownloadCancelled("Скачивание отменено") self._download_async(spec, partial, progress, cancel, notify)
with ( )
httpx.stream("GET", spec.url, follow_redirects=True, timeout=30.0) as response, finally:
partial.open("wb") as output, loop.run_until_complete(loop.shutdown_asyncgens())
): # Unlike asyncio.run(), do not wait for a cancelled OS DNS
response.raise_for_status() # resolver thread. The transfer task and client are already
for chunk in response.iter_bytes(1024 * 1024): # fully closed; a resolver cannot resume the download.
if cancel is not None and cancel.is_set(): loop.close()
raise DownloadCancelled("Скачивание отменено") check_cancel()
received += len(chunk) notify("verifying")
if received > spec.size: if not self._valid_cancellable(partial, spec, check_cancel):
raise ModelError("Размер модели превышает ожидаемый")
output.write(chunk)
digest.update(chunk)
if progress is not None:
progress(received, spec.size)
if cancel is not None and cancel.is_set():
raise DownloadCancelled("Скачивание отменено")
if received != spec.size or digest.hexdigest() != spec.sha256:
raise ModelError("Проверка размера или SHA256 модели не пройдена") raise ModelError("Проверка размера или SHA256 модели не пройдена")
check_cancel()
partial.replace(path) partial.replace(path)
logger.info(
"model.download.completed operation=%s model=%s bytes=%d elapsed_ms=%d",
operation,
spec.id,
spec.size,
int((time.monotonic() - started) * 1000),
)
return path return path
except httpx.HTTPError as exc:
raise ModelError(
"Не удалось скачать модель. Проверьте соединение и повторите"
) from exc
finally: finally:
partial.unlink(missing_ok=True) partial.unlink(missing_ok=True)
except DownloadCancelled:
logger.info(
"model.download.cancelled operation=%s model=%s elapsed_ms=%d",
operation,
spec.id,
int((time.monotonic() - started) * 1000),
)
raise
except Exception as exc:
# Exception text may contain signed redirect URLs or local user paths.
logger.warning(
"model.download.failed operation=%s model=%s error_type=%s",
operation,
spec.id,
type(exc).__name__,
)
if isinstance(exc, httpx.HTTPError):
raise ModelError(
"Не удалось скачать модель. Проверьте соединение и повторите"
) from None
raise
@staticmethod
def _valid_cancellable(path: Path, spec: ModelSpec, check_cancel: Callable[[], None]) -> bool:
if not path.is_file() or path.stat().st_size != spec.size:
return False
digest = hashlib.sha256()
with path.open("rb") as stream:
while block := stream.read(1024 * 1024):
check_cancel()
digest.update(block)
check_cancel()
return digest.hexdigest() == spec.sha256
@staticmethod
async def _download_async(
spec: ModelSpec,
partial: Path,
progress: Callable[[int, int], None] | None,
cancel: threading.Event | None,
notify: Callable[[str], None],
) -> None:
"""Cancel pending socket awaits; await shutdown before returning to caller.
The sync API runs on the existing downloader worker. It owns this event
loop and never leaves a background download or writer after cancellation.
"""
async def transfer() -> None:
notify("connecting")
timeout = httpx.Timeout(30.0, connect=10.0)
async with (
httpx.AsyncClient(timeout=timeout, follow_redirects=True) as client,
client.stream("GET", spec.url) as response,
):
response.raise_for_status()
notify("downloading")
received = 0
with partial.open("wb") as output:
# No chunk-size buffer: surface each available network block.
async for block in response.aiter_bytes():
if cancel is not None and cancel.is_set():
raise DownloadCancelled("Скачивание отменено")
received += len(block)
if received > spec.size:
raise ModelError("Размер модели превышает ожидаемый")
output.write(block)
if progress is not None:
progress(received, spec.size)
# Cached transports may yield synchronously; let cancellation run.
await asyncio.sleep(0)
task = asyncio.create_task(transfer())
try:
while not task.done():
if cancel is not None and cancel.is_set():
task.cancel()
with suppress(asyncio.CancelledError):
await task
raise DownloadCancelled("Скачивание отменено")
await asyncio.wait({task}, timeout=0.1)
await task
finally:
if not task.done():
task.cancel()
with suppress(asyncio.CancelledError):
await task
def delete(self, model_id: str) -> None: def delete(self, model_id: str) -> None:
"""Remove a managed model, refusing to race with a download.""" """Remove a managed model, refusing to race with a download."""

View file

@ -53,6 +53,9 @@ def configure_logging(paths: AppPaths, verbose: bool = False) -> None:
paths: Пути приложения (для log_file). paths: Пути приложения (для log_file).
verbose: Если True — уровень DEBUG, иначе INFO. verbose: Если True — уровень DEBUG, иначе INFO.
""" """
# HTTP redirects may include signed query parameters.
for dependency in ("httpx", "httpcore"):
logging.getLogger(dependency).setLevel(logging.WARNING)
level = logging.DEBUG if verbose else logging.INFO level = logging.DEBUG if verbose else logging.INFO
root_logger = logging.getLogger() root_logger = logging.getLogger()

View file

@ -4,13 +4,15 @@ from __future__ import annotations
import queue import queue
import threading import threading
import time
from collections.abc import Callable from collections.abc import Callable
from dataclasses import replace from dataclasses import replace
from datetime import datetime
import customtkinter as ctk import customtkinter as ctk
from voice_dictation.core.config import ConfigStore from voice_dictation.core.config import ConfigStore
from voice_dictation.core.model_manager import CATALOG, ModelManager from voice_dictation.core.model_manager import CATALOG, DownloadCancelled, ModelError, ModelManager
from voice_dictation.core.paths import AppPaths from voice_dictation.core.paths import AppPaths
@ -58,16 +60,46 @@ def build_recognition_tab(
events: queue.Queue[tuple[str, float]] = queue.Queue() events: queue.Queue[tuple[str, float]] = queue.Queue()
cancel = threading.Event() cancel = threading.Event()
busy = False busy = False
started = 0.0
received = 0
total_bytes = 0
last_update = 0.0
buttons: list[ctk.CTkButton] = [] buttons: list[ctk.CTkButton] = []
journal = ctk.CTkTextbox(parent, width=620, height=100)
journal.pack(anchor="w", padx=12, pady=6)
journal.configure(state="disabled")
def note(message: str) -> None:
journal.configure(state="normal")
journal.insert("end", f"{datetime.now():%H:%M:%S} {message}\n")
if int(journal.index("end-1c").split(".")[0]) > 100:
journal.delete("1.0", "2.0")
journal.see("end")
journal.configure(state="disabled")
stages = {
"checking": "Проверяю установленную модель…",
"connecting": "Подключаюсь к серверу моделей…",
"downloading": "Получаю файл модели…",
"verifying": "Проверяю целостность скачанного файла…",
}
def progress(done: int, total: int) -> None:
nonlocal received, total_bytes, last_update
received, total_bytes = done, total
now = time.monotonic()
if now - last_update >= 0.2 or done == total:
events.put(("progress", done / total if total else 0))
last_update = now
def worker(action: str, model_id: str) -> None: def worker(action: str, model_id: str) -> None:
try: try:
if action == "download": if action == "download":
manager.download( manager.download(
model_id, model_id,
progress=lambda done, total: events.put( progress=progress,
("progress", done / total if total else 0) stage=lambda name: events.put((stages[name], -2)),
),
cancel=cancel, cancel=cancel,
) )
events.put(("Модель скачана и проверена. Можно использовать.", 1)) events.put(("Модель скачана и проверена. Можно использовать.", 1))
@ -84,18 +116,33 @@ def build_recognition_tab(
1 if installed else 0, 1 if installed else 0,
) )
) )
except Exception as exc: except DownloadCancelled:
events.put(("Загрузка отменена. Незавершённый файл удалён.", 0))
except ModelError as exc:
events.put((str(exc), -1)) events.put((str(exc), -1))
except Exception:
events.put(("Не удалось выполнить операцию. Подробности — в журнале приложения.", -1))
def start(action: str) -> None: def start(action: str) -> None:
nonlocal busy nonlocal busy, started, received, total_bytes, last_update
if busy: if busy:
return return
busy = True busy = True
started = time.monotonic()
received = total_bytes = 0
last_update = 0.0
cancel.clear() cancel.clear()
cancel_button.configure(state="normal" if action == "download" else "disabled")
for button in buttons: for button in buttons:
button.configure(state="disabled") button.configure(state="disabled")
status.configure(text="Проверяю модель…" if action == "check" else "Выполняю…") message = {
"check": "Проверяю модель…",
"download": "Подготавливаю загрузку…",
"delete": "Удаляю модель…",
}[action]
status.configure(text=message)
bar.set(0)
note(f"{selected.get()}: {message}")
threading.Thread(target=worker, args=(action, labels[selected.get()]), daemon=True).start() threading.Thread(target=worker, args=(action, labels[selected.get()]), daemon=True).start()
def poll() -> None: def poll() -> None:
@ -108,10 +155,20 @@ def build_recognition_tab(
message, value = events.get_nowait() message, value = events.get_nowait()
if message == "progress": if message == "progress":
bar.set(value) bar.set(value)
elapsed = max(0.1, time.monotonic() - started)
if not cancel.is_set():
status.configure( status.configure(
text=f"Скачивание: {value:.0%}. После загрузки — проверка файла." text=f"Скачивание: {value:.1%} · {received / 1_000_000:.1f} / "
f"{total_bytes / 1_000_000:.1f} МБ · "
f"{received / elapsed / 1_000_000:.1f} МБ/с"
) )
elif value == -2:
note(message)
if not cancel.is_set():
status.configure(text=message)
else: else:
note(message)
cancel_button.configure(state="disabled")
status.configure(text=message) status.configure(text=message)
bar.set(max(0, value)) bar.set(max(0, value))
busy = False busy = False
@ -127,7 +184,19 @@ def build_recognition_tab(
button = ctk.CTkButton(row, text=title, width=110, command=lambda a=action: start(a)) button = ctk.CTkButton(row, text=title, width=110, command=lambda a=action: start(a))
button.pack(side="left", padx=(0, 6)) button.pack(side="left", padx=(0, 6))
buttons.append(button) buttons.append(button)
ctk.CTkButton(row, text="Отменить", width=100, command=cancel.set).pack(side="left")
def request_cancel() -> None:
if not busy or cancel.is_set():
return
cancel.set()
status.configure(text="Отменяю загрузку… Закрываю соединение и удаляю временный файл.")
note("Отмена запрошена; ожидаю завершения операции…")
cancel_button.configure(state="disabled")
cancel_button = ctk.CTkButton(
row, text="Отменить", width=100, command=request_cancel, state="disabled"
)
cancel_button.pack(side="left")
def save() -> None: def save() -> None:
updated = replace( updated = replace(

View file

@ -4,7 +4,7 @@ from __future__ import annotations
import hashlib import hashlib
import threading import threading
from unittest.mock import MagicMock from unittest.mock import AsyncMock, MagicMock
import httpx import httpx
import pytest import pytest
@ -30,10 +30,21 @@ def fixture_model(monkeypatch):
) )
monkeypatch.setattr(module, "CATALOG", (spec,)) monkeypatch.setattr(module, "CATALOG", (spec,))
response = MagicMock() response = MagicMock()
response.iter_bytes.return_value = iter([content[:8], content[8:]]) response.blocks = [content[:8], content[8:]]
async def chunks():
for block in response.blocks:
yield block
response.aiter_bytes = chunks
stream = MagicMock() stream = MagicMock()
stream.__enter__.return_value = response stream.__aenter__ = AsyncMock(return_value=response)
monkeypatch.setattr(module.httpx, "stream", lambda *a, **kw: stream) 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 return spec, content, response
@ -52,7 +63,7 @@ def test_verified_atomic_download(tmp_path, fixture_model):
def test_corrupt_download_never_installed(tmp_path, fixture_model): def test_corrupt_download_never_installed(tmp_path, fixture_model):
spec, _, response = fixture_model spec, _, response = fixture_model
response.iter_bytes.return_value = iter([b"corrupt"]) response.blocks = [b"corrupt"]
manager = ModelManager(tmp_path) manager = ModelManager(tmp_path)
with pytest.raises(ModelError, match="SHA256"): with pytest.raises(ModelError, match="SHA256"):
manager.download(spec.id) manager.download(spec.id)
@ -124,7 +135,7 @@ def test_inference_lease_blocks_delete_and_releases(tmp_path, fixture_model):
@pytest.mark.parametrize("oversize", [False, True]) @pytest.mark.parametrize("oversize", [False, True])
def test_wrong_hash_and_oversize_rejected(tmp_path, fixture_model, oversize): def test_wrong_hash_and_oversize_rejected(tmp_path, fixture_model, oversize):
spec, content, response = fixture_model spec, content, response = fixture_model
response.iter_bytes.return_value = iter([b"x" * (len(content) + int(oversize))]) response.blocks = [b"x" * (len(content) + int(oversize))]
manager = ModelManager(tmp_path) manager = ModelManager(tmp_path)
with pytest.raises(ModelError): with pytest.raises(ModelError):
manager.download(spec.id) manager.download(spec.id)
@ -135,7 +146,7 @@ def test_wrong_hash_and_oversize_rejected(tmp_path, fixture_model, oversize):
def test_precancelled_download_makes_no_request(tmp_path, fixture_model, monkeypatch): def test_precancelled_download_makes_no_request(tmp_path, fixture_model, monkeypatch):
spec, _, _ = fixture_model spec, _, _ = fixture_model
request = MagicMock() request = MagicMock()
monkeypatch.setattr(module.httpx, "stream", request) monkeypatch.setattr(module.httpx, "AsyncClient", request)
cancel = threading.Event() cancel = threading.Event()
cancel.set() cancel.set()
with pytest.raises(DownloadCancelled): with pytest.raises(DownloadCancelled):
@ -151,3 +162,84 @@ def test_partial_symlink_cannot_overwrite_target(tmp_path, fixture_model):
with pytest.raises(ModelError, match="ссылкой"): with pytest.raises(ModelError, match="ссылкой"):
ModelManager(tmp_path).download(spec.id) ModelManager(tmp_path).download(spec.id)
assert target.read_bytes() == b"keep" 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