Skip to content

The agent that grows with you

8.9 KB
Raw Blame
"""A program outside Hermes whose working folder is inside release/ blocks the Desktop swap (#101789).

Real processes on a real Windows host: a helper started with its cwd inside
``release/win-unpacked`` (the shape of Sogou IME's ``SogouCloud.exe``, spawned from a Hermes
window and inheriting its cwd) makes Windows refuse the promotion rename. The failure must name
that program, must never close it without consent, and a consented retry must close exactly it
and finish the swap.
"""

from __future__ import annotations

import contextlib
import json
import subprocess
import sys
import time
from pathlib import Path

import psutil
import pytest

from hermes_cli import desktop_release_holders, main_desktop

pytestmark = pytest.mark.platforms("windows")

_HELPER = "import sys, time\nprint('ready', flush=True)\ntime.sleep(300)\n"


@pytest.fixture
def swap_fixture(tmp_path, monkeypatch):
    desktop_dir = tmp_path / "apps" / "desktop"
    live_root = desktop_dir / "release" / "win-unpacked"
    live_root.mkdir(parents=True)
    (live_root / "Hermes.exe").write_text("old", encoding="utf-8")
    staging = main_desktop._desktop_staging_dir(desktop_dir)
    (staging / "win-unpacked").mkdir(parents=True)
    (staging / "win-unpacked" / "Hermes.exe").write_text("new", encoding="utf-8")
    monkeypatch.setattr(main_desktop, "_DESKTOP_SWAP_RENAME_RETRY_DELAYS_S", (0.2,))
    script = tmp_path / "foreign_helper.py"
    script.write_text(_HELPER, encoding="utf-8")
    helper = subprocess.Popen(
        [sys.executable, str(script)], cwd=live_root, stdout=subprocess.PIPE, text=True,
        creationflags=getattr(subprocess, "CREATE_NO_WINDOW", 0),
    )
    # The child opens its cwd handle during its own startup: wait for it before asserting the lock.
    assert helper.stdout.readline().strip() == "ready"
    try:
        yield desktop_dir, staging, live_root, helper
    finally:
        if helper.poll() is None:
            helper.kill()
            helper.wait(10)


def _promote(desktop_dir: Path, staging: Path) -> tuple[Path | None, str]:
    try:
        return main_desktop._promote_staged_desktop_app(desktop_dir, staging, integrity_check=lambda _p: None), ""
    except RuntimeError as exc:
        return None, str(exc)


def test_blocked_swap_names_the_foreign_holder_and_leaves_it_running(swap_fixture, capsys):
    desktop_dir, staging, live_root, helper = swap_fixture

    promoted, error = _promote(desktop_dir, staging)

    out = capsys.readouterr().out
    assert promoted is None
    assert f"pid {helper.pid}" in error, error  # the update failure names the holder
    assert f"Desktop app folder held by: {psutil.Process(helper.pid).name()} (pid {helper.pid}, " in out, out
    assert helper.poll() is None, "a program outside Hermes was closed without consent"
    assert (live_root / "Hermes.exe").read_text(encoding="utf-8") == "old"


def _consent_for_run(desktop_dir: Path, helper, run_id: str) -> tuple[Path, list]:
    # The venv python.exe may be a launcher with the real interpreter as its child, both inside
    # the folder; the Desktop consents to every process the failure named, so this does too.
    tree = [psutil.Process(helper.pid), *psutil.Process(helper.pid).children(recursive=True)]
    consent = desktop_dir / "release" / ".close-holders-consent.json"
    seen = [{"pid": p.pid, "start_time": p.create_time(), "exe": p.exe()} for p in tree]
    consent.write_text(json.dumps({"written_at": time.time(), "run_id": run_id,
                                   "exes": [s["exe"] for s in seen], "holders": seen}), encoding="utf-8")
    return consent, tree


def test_a_consent_given_for_another_run_closes_nothing_and_is_used_up(swap_fixture, monkeypatch):
    """Review N1: a gateway /update (or any swap not started by the consented retry) never closes."""
    desktop_dir, staging, live_root, helper = swap_fixture
    consent, _tree = _consent_for_run(desktop_dir, helper, "desktop-retry-1")
    monkeypatch.setenv("HERMES_UPDATE_CORRELATION_ID", "gateway-update-7")

    promoted, error = _promote(desktop_dir, staging)

    assert promoted is None and f"pid {helper.pid}" in error, error
    assert helper.poll() is None, "closed on a consent given for another run"
    assert not consent.exists(), "the swap attempt consumes the consent, matching or not"
    assert (live_root / "Hermes.exe").read_text(encoding="utf-8") == "old"


def test_consented_retry_closes_exactly_the_holder_and_promotes(swap_fixture, capsys, monkeypatch):
    desktop_dir, staging, live_root, helper = swap_fixture
    consent, tree = _consent_for_run(desktop_dir, helper, "desktop-retry-1")
    monkeypatch.setenv("HERMES_UPDATE_CORRELATION_ID", "desktop-retry-1")  # windows.ps1 exports its run id

    promoted, error = _promote(desktop_dir, staging)

    assert error == ""
    assert promoted == live_root / "Hermes.exe"
    assert promoted.read_text(encoding="utf-8") == "new"
    assert helper.wait(10) is not None
    assert not [p.pid for p in tree if p.is_running()]
    assert not consent.exists(), "a consent covers one retry only"
    assert "Closed with your consent: " in capsys.readouterr().out


def test_a_partial_close_reports_only_the_holder_still_in_the_way(swap_fixture, tmp_path, capsys, monkeypatch):
    """The consented holder closes but a protected one keeps the folder: the machine lines
    windows.ps1 hands the Desktop must name only the protected one, or the next dialog offers
    to close a program that already exited."""
    desktop_dir, staging, live_root, helper = swap_fixture
    _consent, closed_tree = _consent_for_run(desktop_dir, helper, "desktop-retry-1")
    protected = subprocess.Popen(
        [sys.executable, str(tmp_path / "foreign_helper.py")], cwd=live_root, stdout=subprocess.PIPE,
        text=True, encoding="utf-8", creationflags=getattr(subprocess, "CREATE_NO_WINDOW", 0),
    )
    try:
        assert protected.stdout.readline().strip() == "ready"
        protected_pids = {protected.pid, *(p.pid for p in psutil.Process(protected.pid).children(recursive=True))}
        real_exe = desktop_release_holders._exe_or_empty
        # What psutil answers for a protected process (elevated, another user's): no program path.
        monkeypatch.setattr(desktop_release_holders, "_exe_or_empty",
                            lambda proc: "" if proc.pid in protected_pids else real_exe(proc))
        monkeypatch.setenv("HERMES_UPDATE_CORRELATION_ID", "desktop-retry-1")

        promoted, error = _promote(desktop_dir, staging)

        assert promoted is None and f"pid {protected.pid}" in error, error
        assert helper.wait(10) is not None
        reported = {int(ln.split("(pid ", 1)[1].split(",", 1)[0])
                    for ln in capsys.readouterr().out.splitlines() if "Desktop app folder held by: " in ln}
        assert protected.pid in reported, reported
        assert not reported & {p.pid for p in closed_tree}, f"an exited holder was reported again: {reported}"
        assert (live_root / "Hermes.exe").read_text(encoding="utf-8") == "old"
    finally:
        for proc in [*psutil.Process(protected.pid).children(recursive=True), psutil.Process(protected.pid)]:
            proc.kill()
        protected.wait(10)


def test_a_program_in_a_sibling_unpacked_folder_is_neither_named_nor_closed(swap_fixture, tmp_path, capsys, monkeypatch):
    """Review fold 1: only release/win-unpacked is renamed. A program whose working folder is a
    sibling (a stale win-arm64-unpacked) does not block it, so even a consent naming it must not
    close it, and the failure lines must not offer it."""
    desktop_dir, staging, live_root, helper = swap_fixture
    sibling_dir = live_root.parent / "win-arm64-unpacked"
    sibling_dir.mkdir()
    sibling_tree: list = []
    sibling = subprocess.Popen(
        [sys.executable, str(tmp_path / "foreign_helper.py")], cwd=sibling_dir, stdout=subprocess.PIPE,
        text=True, encoding="utf-8", creationflags=getattr(subprocess, "CREATE_NO_WINDOW", 0),
    )
    try:
        assert sibling.stdout.readline().strip() == "ready"
        sibling_tree.extend([psutil.Process(sibling.pid), *psutil.Process(sibling.pid).children(recursive=True)])
        consent, tree = _consent_for_run(desktop_dir, helper, "desktop-retry-1")
        seen = json.loads(consent.read_text(encoding="utf-8"))
        seen["holders"] += [{"pid": p.pid, "start_time": p.create_time(), "exe": p.exe()} for p in sibling_tree]
        consent.write_text(json.dumps(seen), encoding="utf-8")
        monkeypatch.setenv("HERMES_UPDATE_CORRELATION_ID", "desktop-retry-1")

        promoted, error = _promote(desktop_dir, staging)

        assert error == "" and promoted == live_root / "Hermes.exe"
        assert helper.wait(10) is not None
        assert not [p.pid for p in tree if p.is_running()]
        assert all(p.is_running() for p in sibling_tree), "closed a program that never held the renamed folder"
        assert f"pid {sibling.pid}" not in capsys.readouterr().out
    finally:
        for proc in sibling_tree:
            with contextlib.suppress(psutil.NoSuchProcess):
                proc.kill()
        sibling.wait(10)