Merge #2357 from Antonio-Faure

This commit is contained in:
Bingxi Zhao (Frank)
2026-11-06 01:56:24 +08:00
8 changed files with 251 additions and 7 deletions

View File

@@ -115,6 +115,22 @@ def installed(name: str) -> bool:
return False
def installed_distributions() -> list[str]:
"""Feature distributions this installation actually owns.
Core is deliberately excluded: callers update it separately and pin the
whole set to one target version. Source checkouts return nothing because
their modules are not separate distributions.
"""
if source_checkout():
return []
return [
str(row["distribution"])
for name, row in manifests().items()
if name != "core" and row.get("distribution") and installed(name)
]
def module_enabled(name: str, *, selected: dict[str, bool] | None = None) -> bool:
if name not in manifests():
raise ValueError(f"Unknown module: {name}")

View File

@@ -1510,6 +1510,26 @@ def _complete_restarted_update(runtime_home: Path) -> bool:
return True
def _fail_restarted_update(runtime_home: Path, error: str) -> bool:
"""Record a restart that will not reach readiness, so clients stop waiting.
Without this, a launcher that exits before ``_complete_restarted_update``
leaves the job in ``restarting`` while nothing listens (see #2330).
"""
from deeptutor.services.app_update import UpdateJobStore, update_store_root
store = UpdateJobStore(update_store_root(runtime_home))
try:
job = store.load()
except (OSError, ValueError, KeyError, TypeError, json.JSONDecodeError):
return False
if job.status != "restarting" or job.restart_home != str(runtime_home.resolve()):
return False
store.mark_failed(job.id, error)
return True
def start(
home: str | Path | None = None,
*,
@@ -1823,8 +1843,17 @@ def start(
shutdown_wake.wait(1)
except KeyboardInterrupt:
request_shutdown("SIGINT")
except Exception as exc:
_fail_restarted_update(runtime_home, f"Restart failed: {exc}")
raise
finally:
cleanup()
# A clean stop before readiness is still an incomplete update; leave a
# durable failure instead of a job that polls forever.
_fail_restarted_update(
runtime_home,
"DeepTutor stopped before the update restart completed.",
)
if exit_code:
raise SystemExit(exit_code)

View File

@@ -28,6 +28,13 @@ def build_update_command(target_version: str) -> list[str]:
"created_at": "validation",
}
).target_version
from deeptutor.modules.catalog import installed_distributions
# 1.7 split features into separately versioned distributions. Upgrading
# core alone leaves every installed module pinned to the old version, so
# the restarted app cannot import its own server/web modules (#2330).
specs = [f"deeptutor=={validated}"]
specs.extend(f"{name}=={validated}" for name in installed_distributions())
return [
sys.executable,
"-m",
@@ -36,7 +43,7 @@ def build_update_command(target_version: str) -> list[str]:
"--no-input",
"--disable-pip-version-check",
"--upgrade",
f"deeptutor=={validated}",
*specs,
]
@@ -78,7 +85,7 @@ def _run_logged(command: list[str], *, cwd: Path, log_path: Path) -> int:
return completed.returncode
def _launch_restart(job: UpdateJob, *, log_path: Path) -> None:
def _launch_restart(job: UpdateJob, *, log_path: Path) -> subprocess.Popen[bytes]:
command, home = build_restart_command(job)
kwargs: dict[str, object] = {
"cwd": str(home),
@@ -95,11 +102,25 @@ def _launch_restart(job: UpdateJob, *, log_path: Path) -> None:
else:
kwargs["start_new_session"] = True
with log_path.open("a", encoding="utf-8") as log:
subprocess.Popen( # type: ignore[arg-type,call-overload] # nosec B603
return subprocess.Popen( # type: ignore[arg-type,call-overload] # nosec B603
command, stdout=log, **kwargs
)
# A launcher that cannot even import the new package exits almost immediately.
# Waiting briefly lets the worker record that failure instead of leaving the job
# stuck in ``restarting`` with nothing listening (see #2330).
RESTART_STARTUP_GRACE_SECONDS = 5.0
def _wait_for_launcher_start(process: subprocess.Popen[bytes]) -> None:
try:
exit_code = process.wait(timeout=RESTART_STARTUP_GRACE_SECONDS)
except subprocess.TimeoutExpired:
return
raise RuntimeError(f"Restarted launcher exited with status {exit_code}")
def _log_aborted_recovery(
store: UpdateJobStore, *, original: Exception, load_error: Exception
) -> None:
@@ -126,11 +147,12 @@ def run_update_worker(
parent_pid: int,
wait_for_parent: Callable[[int], None] = wait_for_process_exit,
command_runner: Callable[[list[str], Path, Path], int] | None = None,
restart_launcher: Callable[[UpdateJob, Path], None] | None = None,
restart_launcher: Callable[[UpdateJob, Path], subprocess.Popen[bytes] | None] | None = None,
) -> int:
"""Install the target, then restore the application on either outcome."""
store = UpdateJobStore(store_root)
restart_attempted = False
try:
job = store.load()
if job.status != "handoff":
@@ -146,10 +168,15 @@ def run_update_worker(
if exit_code != 0:
raise RuntimeError(f"pip exited with status {exit_code}")
job = store.mark_restarting(job.id)
(restart_launcher or (lambda value, path: _launch_restart(value, log_path=path)))(
restart_attempted = True
launched = (
restart_launcher or (lambda value, path: _launch_restart(value, log_path=path))
)(
job,
store.log_path,
)
if launched is not None:
_wait_for_launcher_start(launched)
return 0
except Exception as exc:
try:
@@ -163,7 +190,9 @@ def run_update_worker(
try:
if current.status not in {"succeeded", "failed"}:
current = store.mark_failed(current.id, str(exc) or type(exc).__name__)
if current.restart_home and current.restart_argv:
# A launcher that already failed to start will fail again; leave
# the durable error instead of spawning another broken process.
if not restart_attempted and current.restart_home and current.restart_argv:
(restart_launcher or (lambda value, path: _launch_restart(value, log_path=path)))(
current,
store.log_path,

View File

@@ -265,11 +265,17 @@ def detect_installation() -> Installation:
command=f"{sys.executable} -m pip install -U deeptutor",
reason=SYSTEMD_UPDATE_REASON,
)
from deeptutor.modules.catalog import installed_distributions
modules = installed_distributions()
command = "pip install -U deeptutor"
if modules:
command = f"{command} {' '.join(modules)}"
return Installation(
mode="pypi",
current_version=__version__,
automatic_update=True,
command="pip install -U deeptutor",
command=command,
reason="",
)
return Installation(

View File

@@ -20,6 +20,25 @@ def isolated_state(tmp_path, monkeypatch):
monkeypatch.setattr(lifecycle, "state_path", lambda: tmp_path / "modules.json")
def test_installed_distributions_skip_core_and_absent_modules(
monkeypatch: pytest.MonkeyPatch,
) -> None:
monkeypatch.setattr(catalog, "source_checkout", lambda: False)
monkeypatch.setattr(catalog, "installed", lambda name: name in {"server", "web"})
distributions = catalog.installed_distributions()
assert distributions == ["deeptutor-server", "deeptutor-web"]
def test_installed_distributions_are_empty_in_a_source_checkout(
monkeypatch: pytest.MonkeyPatch,
) -> None:
monkeypatch.setattr(catalog, "source_checkout", lambda: True)
assert catalog.installed_distributions() == []
def test_dependent_disable_requires_explicit_order():
assert "reading" in lifecycle.plan("disable", "knowledge")["blocked_by"]
with pytest.raises(lifecycle.ModuleLifecycleError, match="Required by"):

View File

@@ -246,6 +246,44 @@ def test_launcher_completes_update_only_after_restart(tmp_path: Path) -> None:
assert store.load().status == "succeeded"
def test_launcher_fails_update_when_the_restart_never_finishes(tmp_path: Path) -> None:
store = UpdateJobStore(update_store_root(tmp_path))
pending = store.create(current_version="1.6.1", target_version="1.7.0")
store.prepare_handoff(
pending.id,
home=tmp_path,
restart_argv=["start", "--home", str(tmp_path.resolve())],
)
store.mark_running(pending.id)
store.mark_restarting(pending.id)
assert launcher._fail_restarted_update(tmp_path, "backend exited with code 1") is True
job = store.load()
assert job.status == "failed"
assert job.error == "backend exited with code 1"
def test_launcher_failure_hook_ignores_other_homes_and_states(tmp_path: Path) -> None:
other = tmp_path / "other"
store = UpdateJobStore(update_store_root(tmp_path))
pending = store.create(current_version="1.6.1", target_version="1.7.0")
store.prepare_handoff(
pending.id,
home=tmp_path,
restart_argv=["start", "--home", str(tmp_path.resolve())],
)
# Still pending: the handoff has not reached the restart phase.
assert launcher._fail_restarted_update(tmp_path, "too early") is False
assert store.load().status == "handoff"
store.mark_running(pending.id)
store.mark_restarting(pending.id)
# A different runtime home must not touch this job.
assert launcher._fail_restarted_update(other, "wrong home") is False
assert store.load().status == "restarting"
def test_packaged_web_cache_refreshes_when_public_settings_change(tmp_path: Path) -> None:
packaged = tmp_path / "pkg"
(packaged / ".next").mkdir(parents=True)

View File

@@ -92,6 +92,89 @@ def test_worker_recovery_reports_and_skips_on_corrupt_state(tmp_path: Path) -> N
assert "pip exited with status 7" in log
def test_worker_marks_failed_when_the_launcher_exits_early(tmp_path: Path) -> None:
store, _job = _handoff_job(tmp_path)
launches: list[UpdateJob] = []
class ExitedProcess:
def wait(self, timeout: float | None = None) -> int:
return 23
def restart(value: UpdateJob, _log_path: Path) -> ExitedProcess:
launches.append(value)
return ExitedProcess()
result = run_update_worker(
store_root=store.root,
parent_pid=123,
wait_for_parent=lambda _pid: None,
command_runner=lambda _command, _cwd, _log: 0,
restart_launcher=restart,
)
assert result == 1
assert len(launches) == 1, "a launcher that just failed must not be spawned again"
job = store.load()
assert job.status == "failed"
assert job.error is not None and "exited with status 23" in job.error
def test_worker_leaves_a_live_launcher_in_restarting(
tmp_path: Path, monkeypatch: pytest.MonkeyPatch
) -> None:
store, _job = _handoff_job(tmp_path)
monkeypatch.setattr("deeptutor.runtime.update_worker.RESTART_STARTUP_GRACE_SECONDS", 0.0)
class LiveProcess:
def wait(self, timeout: float | None = None) -> int:
import subprocess
raise subprocess.TimeoutExpired("launcher", timeout or 0)
result = run_update_worker(
store_root=store.root,
parent_pid=123,
wait_for_parent=lambda _pid: None,
command_runner=lambda _command, _cwd, _log: 0,
restart_launcher=lambda _job, _log: LiveProcess(),
)
assert result == 0
assert store.load().status == "restarting"
def test_update_command_upgrades_every_installed_module(monkeypatch: pytest.MonkeyPatch) -> None:
from deeptutor.modules import catalog
monkeypatch.setattr(
catalog,
"installed_distributions",
lambda: ["deeptutor-server", "deeptutor-web", "deeptutor-parsing"],
)
command = build_update_command("1.7.2")
assert command[-4:] == [
"deeptutor==1.7.2",
"deeptutor-server==1.7.2",
"deeptutor-web==1.7.2",
"deeptutor-parsing==1.7.2",
]
def test_update_command_keeps_core_only_installs_light(monkeypatch: pytest.MonkeyPatch) -> None:
from deeptutor.modules import catalog
monkeypatch.setattr(catalog, "installed_distributions", lambda: [])
command = build_update_command("1.7.2")
# Compare package arguments only: the interpreter path itself can contain
# "deeptutor-" when the venv is named "deeptutor-dev-venv".
specs = command[command.index("--upgrade") + 1 :]
assert specs == ["deeptutor==1.7.2"]
def test_update_command_rejects_non_stable_or_injected_versions() -> None:
with pytest.raises(ValueError):
build_update_command("1.7.0rc1")

View File

@@ -169,6 +169,30 @@ def test_detect_installation_keeps_source_and_docker_host_managed(
assert installation.automatic_update is True
def test_detect_installation_manual_command_includes_installed_modules(
monkeypatch: pytest.MonkeyPatch,
tmp_path: Path,
) -> None:
from deeptutor.modules import catalog
monkeypatch.setattr(app_update, "_running_in_container", lambda: False)
monkeypatch.setattr(app_update, "_running_from_source_checkout", lambda: False)
monkeypatch.setattr(app_update, "_distribution_direct_url", lambda: {})
monkeypatch.setattr(app_update, "running_under_systemd_service", lambda: False)
monkeypatch.setattr(app_update.sys, "prefix", str(tmp_path / "venv"))
monkeypatch.setattr(app_update.sys, "base_prefix", str(tmp_path / "base"))
monkeypatch.setattr(
catalog,
"installed_distributions",
lambda: ["deeptutor-server", "deeptutor-reading"],
)
installation = app_update.detect_installation()
assert installation.automatic_update is True
assert installation.command == ("pip install -U deeptutor deeptutor-server deeptutor-reading")
def test_systemd_service_cgroup_disables_in_app_update(
monkeypatch: pytest.MonkeyPatch, tmp_path: Path
) -> None: