From 92e6162f6f9debd34534a84a9904089c3eae5a57 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 4 Dec 2026 14:50:35 +0000 Subject: [PATCH 1/2] Template 0.1.47: the Windows uninstall stops the app's running processes Testers who uninstalled while Jupyter was open found the app folder left behind (python.exe, its DLLs, Lib, DLLs, Library: 0.4 to 4 GB): Windows cannot delete files in use, and the restart-time deletion the uninstaller asks for needs an administrator. pre_uninstall.bat now stops every process whose program is inside the app folder (sparing the uninstaller and its helpers) and waits for them, so the uninstall removes the whole folder. The installer round trip's --busy mode becomes strict: the running Python of the app must be stopped and the folder gone. Migration 0.1.47 adds the lines before "echo Pre-uninstall completed!" (line endings kept, SKIPPED when that line is missing). Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01G3qp9AoUT3RtgWWsiVVarX --- .github/workflows/installer_roundtrip.yml | 4 +- .template_sync/manifest.yaml | 5 +- .../migrations/v0_1_46_to_v0_1_47.py | 72 ++++++++++ .tools/docs/migration_0_1_47.md | 39 +++++ app/bash_bat_scripts/pre_uninstall.bat | 4 + tests/_v0_1_46.py | 3 + tests/_v0_1_47.py | 31 ++++ tests/smoke/installer_roundtrip.py | 25 ++-- tests/test_template_sync_0_1_47.py | 133 ++++++++++++++++++ 9 files changed, 300 insertions(+), 16 deletions(-) create mode 100644 .template_sync/migrations/v0_1_46_to_v0_1_47.py create mode 100644 .tools/docs/migration_0_1_47.md create mode 100644 tests/_v0_1_47.py create mode 100644 tests/test_template_sync_0_1_47.py diff --git a/.github/workflows/installer_roundtrip.yml b/.github/workflows/installer_roundtrip.yml index a707655..1c6e6d2 100644 --- a/.github/workflows/installer_roundtrip.yml +++ b/.github/workflows/installer_roundtrip.yml @@ -3,7 +3,7 @@ name: Installer round trip # Builds a real installer of a small demo app made from this template (tests/smoke/make_demo_app.py: the placeholders filled in, the # release scripts run as release_constructor.yml runs them, the same constructor environment and build script), installs it silently, # checks the install, uninstalls it silently and checks what is left (tests/smoke/installer_roundtrip.py). On Windows a second round trip -# keeps a Python of the app running during the uninstall and prints what stays of the folder (diagnosis only). +# keeps a Python of the app running during the uninstall, which must stop it and still remove the whole folder. # It runs on the pull requests that change what an installer is made of, and by hand. It does not run in the apps created from the template. on: pull_request: @@ -76,7 +76,7 @@ jobs: - name: Install, check, uninstall, check run: python tests/smoke/installer_roundtrip.py "$DEMO/dist" "${{ runner.temp }}/rt/Demo_App" --logs "$ARTIFACTS" - - name: 'Windows: uninstall while a Python of the app runs (prints what stays)' + - name: 'Windows: uninstall while a Python of the app runs (it is stopped, the folder is removed)' if: runner.os == 'Windows' && !cancelled() run: python tests/smoke/installer_roundtrip.py "$DEMO/dist" "${{ runner.temp }}/rt/Demo_App_busy" --busy --logs "$ARTIFACTS" diff --git a/.template_sync/manifest.yaml b/.template_sync/manifest.yaml index ad9389a..abe7b69 100644 --- a/.template_sync/manifest.yaml +++ b/.template_sync/manifest.yaml @@ -1,4 +1,4 @@ -template_version: 0.1.46 +template_version: 0.1.47 migrations: - from: 0.0.0 to: 0.0.1 @@ -144,3 +144,6 @@ migrations: - from: 0.1.45 to: 0.1.46 script: migrations/v0_1_45_to_v0_1_46.py + - from: 0.1.46 + to: 0.1.47 + script: migrations/v0_1_46_to_v0_1_47.py diff --git a/.template_sync/migrations/v0_1_46_to_v0_1_47.py b/.template_sync/migrations/v0_1_46_to_v0_1_47.py new file mode 100644 index 0000000..f35b24c --- /dev/null +++ b/.template_sync/migrations/v0_1_46_to_v0_1_47.py @@ -0,0 +1,72 @@ +"""Template 0.1.46 -> 0.1.47: on Windows the uninstall stops the app's running processes, so it can remove the whole app folder. + +Design note: https://github.com/CellMigrationLab/LabConstrictor/blob/main/.tools/docs/migration_0_1_47.md + +Windows cannot delete a file that a running process uses. Testers who uninstalled while Jupyter was open found the app folder left behind +(python.exe, its DLLs, Lib, DLLs and Library: 0.4 to 4 GB). The uninstaller marks such files for deletion at the next restart, but Windows +does that only for an administrator, and the apps are installed for one user, so the files stayed for good. + +What this changes in an app repository (idempotent, never deletes anything, never raises for a customised file): + +1. app/bash_bat_scripts/pre_uninstall.bat gets four lines just before its line `echo Pre-uninstall completed!`: three REM lines and one + PowerShell command that stops every process whose program is inside the app folder (a Jupyter server and its kernels, a Napari or + Fiji tool worker), except the uninstaller and its helpers, and waits up to 15 s for each to end. A script without that line is left as it + is (SKIPPED, with what to do by hand). The file keeps its own line endings. + +Linux and macOS are not changed: a running process does not stop the removal of its files there. The change reaches users with the app's next +release. +""" +from __future__ import annotations + +from pathlib import Path +from typing import Any + +DOCS_URL = "https://github.com/CellMigrationLab/LabConstrictor/blob/main/.tools/docs/migration_0_1_47.md" +TAG = "[migration 0.1.47]" +PRE_UNINSTALL_BAT = Path("app/bash_bat_scripts/pre_uninstall.bat") +ANCHOR = "echo Pre-uninstall completed!" +STOP_LINES = ( + 'REM Stop the processes of this app that still run (a Jupyter server and its kernels, a Napari or Fiji tool worker): Windows cannot delete', + 'REM a file a process uses, so the uninstall left the app folder behind (template 0.1.47). Only programs inside this app folder are stopped,', + 'REM never this uninstaller or its own helpers; unsaved notebook edits since the last autosave are lost.', + 'powershell -NoProfile -ExecutionPolicy Bypass -Command "$ErrorActionPreference=\'SilentlyContinue\'; $root=[IO.Path]::GetFullPath($env:PREFIX).TrimEnd(\'\\\')+\'\\\'; $all=@(Get-CimInstance Win32_Process); $keep=@{}; $id=[int]$PID; while($id -and -not $keep.ContainsKey($id)){ $keep[$id]=1; $id=[int](($all | Where-Object { [int]$_.ProcessId -eq $id } | Select-Object -First 1).ParentProcessId) }; $own=@($all | Where-Object { $_.ExecutablePath -and $_.ExecutablePath.StartsWith($root, [StringComparison]::OrdinalIgnoreCase) -and -not $keep.ContainsKey([int]$_.ProcessId) -and $_.Name -ne \'_conda.exe\' -and $_.Name -notlike \'Uninstall-*\' }); foreach($p in $own){ Write-Output (\'Stopping \' + $p.Name + \' (process \' + $p.ProcessId + \') started from \' + $root); Stop-Process -Id ([int]$p.ProcessId) -Force }; foreach($p in $own){ Wait-Process -Id ([int]$p.ProcessId) -Timeout 15 }; if($own.Count -eq 0){ Write-Output \'No process of the app is running\' }"', +) +BY_HAND = f"add the lines of STOP_LINES in this migration before the end of the script (see {DOCS_URL})" + + +def log(message: str) -> None: + print(f"{TAG} {message}") + + +def add_stop_lines(path: Path) -> str: + text = path.read_bytes().decode("utf-8") + if STOP_LINES[0] in text: + return "unchanged: already stops the app's running processes" + lines = text.splitlines(keepends=True) + hits = [index for index, line in enumerate(lines) if line.rstrip("\r\n").strip() == ANCHOR] + if len(hits) != 1: + return f"SKIPPED: no single line {ANCHOR!r} (changed by hand), so it was left unchanged. By hand: {BY_HAND}" + newline = "\r\n" if "\r\n" in text else "\n" + index = hits[0] + lines[index:index] = [line + newline for line in STOP_LINES] + path.write_bytes("".join(lines).encode("utf-8")) + return "updated: the uninstall stops the app's running processes first, so it removes the whole app folder" + + +def migrate(repo_root: Path, context: dict[str, Any]) -> None: + """Apply the 0.1.47 change (idempotent, never raises for a customised file, creates and deletes nothing).""" + _ = context + path = repo_root / PRE_UNINSTALL_BAT + if not path.is_file(): + log(f"{PRE_UNINSTALL_BAT}: not present in this repository (nothing was created)") + log("done: no repository changes were required.") + return + try: + status = add_stop_lines(path) + except (OSError, UnicodeDecodeError) as exc: + status = f"SKIPPED: {exc}; left unchanged. See {DOCS_URL}" + log(f"{PRE_UNINSTALL_BAT}: {status}") + if status.startswith("updated"): + log(f"done: 1 change(s). It reaches users with the next release of the app. See {DOCS_URL}") + else: + log("done: no repository changes were required.") diff --git a/.tools/docs/migration_0_1_47.md b/.tools/docs/migration_0_1_47.md new file mode 100644 index 0000000..62b4ee6 --- /dev/null +++ b/.tools/docs/migration_0_1_47.md @@ -0,0 +1,39 @@ +# Template 0.1.47: the Windows uninstall stops the app's running processes + +Design note for the 0.1.47 migration (`.template_sync/migrations/v0_1_46_to_v0_1_47.py`). + +## Why + +Testers of LabConstrictor-CAREamics 0.0.5 uninstalled the app on two Windows 11 computers. Both times, part of the app folder +(`%LOCALAPPDATA%\`) stayed behind: `python.exe`, `python3.dll`, `python312.dll`, the Visual C++ runtime DLLs and the folders `DLLs`, +`Lib`, `Library` and ``. That was 433 MB on one computer and 4.1 GB on the other. Jupyter was still open. + +Windows cannot delete a file that a running process uses. The uninstaller marks such files for deletion at the next restart, but Windows +does that only for an administrator, and the apps are installed for one user. The installer round trip of the template CI +(`.github/workflows/installer_roundtrip.yml`, `--busy`) showed the same thing with one Python process of the app running: those files stayed, +even after the process ended. + +## What changes + +`app/bash_bat_scripts/pre_uninstall.bat` now ends with one PowerShell command (after three REM lines) that: + +* stops every process whose program is inside the app folder: a Jupyter server and its kernels, a Napari or Fiji tool worker, any other + Python of the app; +* leaves the uninstaller alone: its own process chain, `_conda.exe` and `Uninstall-*.exe`; +* waits up to 15 s for each process to end. + +The uninstall then removes the whole folder. Notebook edits made since Jupyter's last autosave (every 2 minutes by default) are lost. The +installer round trip checks this on Windows: a running Python of the app is stopped, and the folder is gone. + +Linux and macOS do not change: a running process does not stop the removal of its files there. + +## What the migration does + +It adds the four lines just before the line `echo Pre-uninstall completed!` of `pre_uninstall.bat`, keeping the file's line endings. A +script that already has them is left as it is. So is a script without that line (SKIPPED: add the lines by hand). The change reaches users +with the app's next release. + +## Removing what an older uninstall left + +Close Jupyter, Napari and Fiji (or restart the computer), then delete the folder `%LOCALAPPDATA%\`. It holds only the app's program files; +notebooks, models and results are in the app's data folder, which the uninstall keeps. diff --git a/app/bash_bat_scripts/pre_uninstall.bat b/app/bash_bat_scripts/pre_uninstall.bat index 14cdff0..67e5af8 100644 --- a/app/bash_bat_scripts/pre_uninstall.bat +++ b/app/bash_bat_scripts/pre_uninstall.bat @@ -5,5 +5,9 @@ IF ERRORLEVEL 1 IF EXIST "%USERPROFILE%\.labconstrictor\apps\PROJECT_NAME.json" "%PREFIX%\python.exe" -c "from menuinst.api import remove; import os; remove(os.path.join(r'%PREFIX%', 'PROJECT_NAME', 'notebook_launcher.json'))" SET "ARP_KEY=HKCU\Software\Microsoft\Windows\CurrentVersion\Uninstall\UNDERSCORED_PROJECT_NAME" reg delete "%ARP_KEY%" /f >NUL 2>&1 +REM Stop the processes of this app that still run (a Jupyter server and its kernels, a Napari or Fiji tool worker): Windows cannot delete +REM a file a process uses, so the uninstall left the app folder behind (template 0.1.47). Only programs inside this app folder are stopped, +REM never this uninstaller or its own helpers; unsaved notebook edits since the last autosave are lost. +powershell -NoProfile -ExecutionPolicy Bypass -Command "$ErrorActionPreference='SilentlyContinue'; $root=[IO.Path]::GetFullPath($env:PREFIX).TrimEnd('\')+'\'; $all=@(Get-CimInstance Win32_Process); $keep=@{}; $id=[int]$PID; while($id -and -not $keep.ContainsKey($id)){ $keep[$id]=1; $id=[int](($all | Where-Object { [int]$_.ProcessId -eq $id } | Select-Object -First 1).ParentProcessId) }; $own=@($all | Where-Object { $_.ExecutablePath -and $_.ExecutablePath.StartsWith($root, [StringComparison]::OrdinalIgnoreCase) -and -not $keep.ContainsKey([int]$_.ProcessId) -and $_.Name -ne '_conda.exe' -and $_.Name -notlike 'Uninstall-*' }); foreach($p in $own){ Write-Output ('Stopping ' + $p.Name + ' (process ' + $p.ProcessId + ') started from ' + $root); Stop-Process -Id ([int]$p.ProcessId) -Force }; foreach($p in $own){ Wait-Process -Id ([int]$p.ProcessId) -Timeout 15 }; if($own.Count -eq 0){ Write-Output 'No process of the app is running' }" echo Pre-uninstall completed! SetLocal EnableDelayedExpansion diff --git a/tests/_v0_1_46.py b/tests/_v0_1_46.py index 763b376..4483764 100644 --- a/tests/_v0_1_46.py +++ b/tests/_v0_1_46.py @@ -8,6 +8,8 @@ from pathlib import Path +from _v0_1_47 import before_0_1_47 + PIN_0_1_45 = "v0.3.0-alpha.5" PIN_0_1_46 = "v0.3.0-alpha.6" PINNED_FILES = (Path("app/bash_bat_scripts/post_install.sh"), Path("app/bash_bat_scripts/post_install.bat")) @@ -15,6 +17,7 @@ def before_0_1_46(relative: Path | str, data: bytes) -> bytes: """`data` (a live template file at `relative`) with the 0.1.46 pin moved back; any other file is returned as it is.""" + data = before_0_1_47(relative, data) if Path(relative) not in PINNED_FILES: return data return data.replace(PIN_0_1_46.encode(), PIN_0_1_45.encode()) diff --git a/tests/_v0_1_47.py b/tests/_v0_1_47.py new file mode 100644 index 0000000..2d063ec --- /dev/null +++ b/tests/_v0_1_47.py @@ -0,0 +1,31 @@ +"""Helper of the tests: a live template file as it was before template 0.1.47. + +Template 0.1.47 adds the lines that stop the app's running processes to pre_uninstall.bat. The tests of the older migrations compare with +the live files; `before_0_1_47` gives the bytes of a live file without those lines, so they keep checking what they checked. The change +itself is tested in test_template_sync_0_1_47.py. +""" +from __future__ import annotations + +import importlib.util +from pathlib import Path + +ROOT = Path(__file__).resolve().parents[1] +PRE_UNINSTALL_BAT = Path("app/bash_bat_scripts/pre_uninstall.bat") + + +def _stop_lines() -> tuple[str, ...]: + spec = importlib.util.spec_from_file_location("migration_0_1_47_helper", ROOT / ".template_sync/migrations/v0_1_46_to_v0_1_47.py") + assert spec is not None and spec.loader is not None + module = importlib.util.module_from_spec(spec) + spec.loader.exec_module(module) + return tuple(module.STOP_LINES) + + +def before_0_1_47(relative: Path | str, data: bytes) -> bytes: + """`data` (a live template file at `relative`) without the 0.1.47 lines; any other file is returned as it is.""" + if Path(relative) != PRE_UNINSTALL_BAT: + return data + text = data.decode("utf-8") + for newline in ("\r\n", "\n"): + text = text.replace("".join(line + newline for line in _stop_lines()), "") + return text.encode("utf-8") diff --git a/tests/smoke/installer_roundtrip.py b/tests/smoke/installer_roundtrip.py index 75f5afe..e280b48 100644 --- a/tests/smoke/installer_roundtrip.py +++ b/tests/smoke/installer_roundtrip.py @@ -11,8 +11,8 @@ * Windows: no "Installed apps" entry points to the folder any more. --busy (Windows): a Python process started from the install folder runs during the uninstall, as Jupyter, Napari or Fiji's tool worker -may. What stays of the folder is printed (files in use cannot be deleted; the uninstaller marks them for removal at the next restart), and -only the "Installed apps" and registry checks fail the run: this mode diagnoses, it does not decide what the uninstaller should do. +may. pre_uninstall.bat stops it (template 0.1.47), so the same checks hold: the folder is gone (before, the files the process used stayed, +and Windows does not delete them at the next restart for a per-user install), and the process was stopped. Usage: python tests/smoke/installer_roundtrip.py INSTALLER_DIR PREFIX [--busy] [--logs DIR] (PREFIX: a folder that does not exist yet, without spaces; LC_HOME is set to a fresh folder next to it) @@ -179,14 +179,13 @@ def leftovers(prefix: Path) -> list[str]: return lines -def check_uninstalled(prefix: Path, env: dict[str, str], other: Path, strict_folder: bool) -> None: +def check_uninstalled(prefix: Path, env: dict[str, str], other: Path) -> None: left = leftovers(prefix) for line in left: print(line, flush=True) - if left and strict_folder: + if left: raise AssertionError(f"the uninstall left the install folder: {left[0]}") - if not left: - ok("the install folder is gone") + ok("the install folder is gone") entry = Path(env["LC_HOME"]) / "apps" / f"{APP}.json" if entry.exists(): raise AssertionError(f"the registry entry of the app is still there: {entry}") @@ -206,7 +205,7 @@ def main() -> int: parser.add_argument("installer_dir", type=Path) parser.add_argument("prefix", type=Path) parser.add_argument("--version", default="1.2.3") - parser.add_argument("--busy", action="store_true", help="Windows: a Python of the app runs during the uninstall (diagnosis)") + parser.add_argument("--busy", action="store_true", help="Windows: a Python of the app runs during the uninstall, which must stop it") parser.add_argument("--logs", type=Path, default=Path("artifacts")) args = parser.parse_args() prefix: Path = args.prefix.absolute() @@ -224,15 +223,15 @@ def main() -> int: busy = start_busy_process(prefix) if args.busy else None try: uninstall(prefix, env) - check_uninstalled(prefix, env, other, strict_folder=busy is None) - finally: if busy is not None: + if busy.poll() is None: + raise AssertionError(f"the uninstall did not stop the app's running process {busy.pid}") + ok(f"the uninstall stopped the app's running process {busy.pid}") + check_uninstalled(prefix, env, other) + finally: + if busy is not None and busy.poll() is None: busy.kill() busy.wait() - time.sleep(5) - step("After the busy process ended") - for line in leftovers(prefix) or [f"{prefix} is gone"]: - print(line, flush=True) print("\ninstaller round trip: all checks passed") return 0 diff --git a/tests/test_template_sync_0_1_47.py b/tests/test_template_sync_0_1_47.py new file mode 100644 index 0000000..adfb036 --- /dev/null +++ b/tests/test_template_sync_0_1_47.py @@ -0,0 +1,133 @@ +"""Tests of the 0.1.47 migration: on Windows the uninstall stops the app's running processes (pre_uninstall.bat), so it removes the whole folder.""" +from __future__ import annotations + +import importlib.util +import re +import shutil +import subprocess +import sys +import tempfile +import unittest +from contextlib import redirect_stdout +from io import StringIO +from pathlib import Path +from types import ModuleType + +ROOT = Path(__file__).resolve().parents[1] +MIGRATION_PATH = ROOT / ".template_sync/migrations/v0_1_46_to_v0_1_47.py" +FILLED = (("UNDERSCORED_PROJECT_NAME", "Cool_App"), ("PROJECT_NAME", "Cool App")) + + +def load(path: Path, name: str) -> ModuleType: + spec = importlib.util.spec_from_file_location(name, path) + assert spec is not None and spec.loader is not None + module = importlib.util.module_from_spec(spec) + spec.loader.exec_module(module) + return module + + +MIGRATION = load(MIGRATION_PATH, "migration_0_1_47") +BAT = MIGRATION.PRE_UNINSTALL_BAT + + +def live(relative: Path) -> bytes: + return (ROOT / relative).read_bytes() + + +def filled(data: bytes) -> bytes: + text = data.decode("utf-8") + for name, value in FILLED: + text = text.replace(name, value) + return text.encode("utf-8") + + +class TemplateTests(unittest.TestCase): + def test_the_lines_come_once_just_before_the_last_message(self) -> None: + lines = live(BAT).decode("utf-8").splitlines() + start = lines.index(MIGRATION.STOP_LINES[0]) + self.assertEqual(tuple(lines[start : start + len(MIGRATION.STOP_LINES)]), MIGRATION.STOP_LINES) + self.assertEqual(lines[start + len(MIGRATION.STOP_LINES)], MIGRATION.ANCHOR) + self.assertEqual(sum(line == MIGRATION.STOP_LINES[0] for line in lines), 1) + + def test_the_command_survives_cmd_and_spares_the_uninstaller(self) -> None: + command = MIGRATION.STOP_LINES[-1] + self.assertTrue(command.startswith("powershell -NoProfile -ExecutionPolicy Bypass -Command \"")) + self.assertTrue(command.endswith('"')) + self.assertEqual(command.count('"'), 2, "one quoted argument: cmd passes it whole") + for character in ("%", "!"): + self.assertNotIn(character, command, "cmd would expand it") + for spared in ("$keep", "'_conda.exe'", "'Uninstall-*'", "$env:PREFIX", "StartsWith($root"): + self.assertIn(spared, command) + for name in ("UNDERSCORED_PROJECT_NAME", "PROJECT_NAME", "BASE_PATH"): + self.assertNotIn(name, "".join(MIGRATION.STOP_LINES), "no placeholder: the lines are the same in every app") + + def test_the_manifest_lists_the_migration_and_the_version(self) -> None: + text = (ROOT / ".template_sync/manifest.yaml").read_text(encoding="utf-8") + self.assertRegex(text, r"template_version: 0\.1\.(4[7-9]|[5-9][0-9])\b") + self.assertIn("script: migrations/v0_1_46_to_v0_1_47.py", text) + self.assertTrue((ROOT / ".tools/docs/migration_0_1_47.md").is_file()) + + def test_the_older_tests_see_the_0_1_46_file(self) -> None: + from _v0_1_47 import before_0_1_47 + + old = before_0_1_47(BAT, live(BAT)).decode("utf-8") + self.assertNotIn(MIGRATION.STOP_LINES[0], old) + self.assertIn(MIGRATION.ANCHOR, old) + self.assertEqual(before_0_1_47("construct.yaml", b"x"), b"x") + + +class MigrationTests(unittest.TestCase): + def setUp(self) -> None: + from _v0_1_47 import before_0_1_47 + + self.repo = Path(tempfile.mkdtemp(prefix="lc_0_1_47_")) + self.bat = self.repo / BAT + self.bat.parent.mkdir(parents=True) + self.bat.write_bytes(filled(before_0_1_47(BAT, live(BAT)))) + + def tearDown(self) -> None: + shutil.rmtree(self.repo, ignore_errors=True) + + def run_migration(self) -> str: + out = StringIO() + with redirect_stdout(out): + MIGRATION.migrate(self.repo, {}) + return out.getvalue() + + def test_an_app_of_0_1_46_gets_the_template_file_and_a_second_run_changes_nothing(self) -> None: + log = self.run_migration() + self.assertEqual(self.bat.read_bytes(), filled(live(BAT))) + self.assertIn("1 change(s)", log) + self.assertIn("unchanged: already stops", self.run_migration()) + + def test_crlf_line_endings_are_kept(self) -> None: + self.bat.write_bytes(self.bat.read_bytes().replace(b"\r\n", b"\n").replace(b"\n", b"\r\n")) + self.run_migration() + expected = filled(live(BAT)).replace(b"\r\n", b"\n").replace(b"\n", b"\r\n") + self.assertEqual(self.bat.read_bytes(), expected) + + def test_a_script_without_the_last_message_is_left_alone(self) -> None: + self.bat.write_bytes(self.bat.read_bytes().replace(MIGRATION.ANCHOR.encode(), b"echo done")) + before = self.bat.read_bytes() + log = self.run_migration() + self.assertEqual(self.bat.read_bytes(), before) + self.assertIn("SKIPPED", log) + + def test_a_missing_script_is_not_created(self) -> None: + self.bat.unlink() + self.assertIn("not present", self.run_migration()) + self.assertFalse(self.bat.exists()) + + def test_the_sync_script_runs_the_migration_from_0_1_46(self) -> None: + shutil.copytree(ROOT / ".template_sync", self.repo / ".template_sync") + manifest = self.repo / ".template_sync/manifest.yaml" + manifest.write_text(re.sub(r"template_version: [0-9.]+", "template_version: 0.1.47", manifest.read_text(encoding="utf-8")), encoding="utf-8") + command = [sys.executable, str(self.repo / ".template_sync/sync.py"), "--from-version", "0.1.46", "--to-version", "0.1.47", "--repository-root", str(self.repo)] + result = subprocess.run(command, capture_output=True, text=True, check=False) + self.assertEqual(result.returncode, 0, result.stdout + result.stderr) + self.assertIn("[migration 0.1.47]", result.stdout) + self.assertEqual(self.bat.read_bytes(), filled(live(BAT))) + + +if __name__ == "__main__": + unittest.main() From a439090530a8fb4a7d2cbd2a8d339c403b841a0e Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 4 Dec 2026 15:01:42 +0000 Subject: [PATCH 2/2] 0.1.47: the app folder is the folder of pre_uninstall.bat, PowerShell by full path, a log of what was stopped The busy round trip found the running Python of the app still running after the uninstall, with nothing to show why. The command now takes the app folder from %~dp0 (not the PREFIX variable), calls PowerShell by its full path and writes %TEMP%\labconstrictor_pre_uninstall.log, which the uninstaller shows and the round trip prints and uploads. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01G3qp9AoUT3RtgWWsiVVarX --- .template_sync/migrations/v0_1_46_to_v0_1_47.py | 15 +++++++++------ .tools/docs/migration_0_1_47.md | 8 +++++--- app/bash_bat_scripts/pre_uninstall.bat | 8 +++++--- tests/smoke/installer_roundtrip.py | 6 ++++++ tests/test_template_sync_0_1_47.py | 16 +++++++++------- 5 files changed, 34 insertions(+), 19 deletions(-) diff --git a/.template_sync/migrations/v0_1_46_to_v0_1_47.py b/.template_sync/migrations/v0_1_46_to_v0_1_47.py index f35b24c..2ac914e 100644 --- a/.template_sync/migrations/v0_1_46_to_v0_1_47.py +++ b/.template_sync/migrations/v0_1_46_to_v0_1_47.py @@ -8,9 +8,10 @@ What this changes in an app repository (idempotent, never deletes anything, never raises for a customised file): -1. app/bash_bat_scripts/pre_uninstall.bat gets four lines just before its line `echo Pre-uninstall completed!`: three REM lines and one - PowerShell command that stops every process whose program is inside the app folder (a Jupyter server and its kernels, a Napari or - Fiji tool worker), except the uninstaller and its helpers, and waits up to 15 s for each to end. A script without that line is left as it +1. app/bash_bat_scripts/pre_uninstall.bat gets six lines just before its line `echo Pre-uninstall completed!`: three REM lines, the app folder + (the folder of the script), one PowerShell command that stops every process whose program is inside the app folder (a Jupyter server and its kernels, a Napari or + Fiji tool worker), except the uninstaller and its helpers, and waits up to 15 s for each to end, and a line that shows its log + (%TEMP%\labconstrictor_pre_uninstall.log). A script without that line is left as it is (SKIPPED, with what to do by hand). The file keeps its own line endings. Linux and macOS are not changed: a running process does not stop the removal of its files there. The change reaches users with the app's next @@ -27,9 +28,11 @@ ANCHOR = "echo Pre-uninstall completed!" STOP_LINES = ( 'REM Stop the processes of this app that still run (a Jupyter server and its kernels, a Napari or Fiji tool worker): Windows cannot delete', - 'REM a file a process uses, so the uninstall left the app folder behind (template 0.1.47). Only programs inside this app folder are stopped,', - 'REM never this uninstaller or its own helpers; unsaved notebook edits since the last autosave are lost.', - 'powershell -NoProfile -ExecutionPolicy Bypass -Command "$ErrorActionPreference=\'SilentlyContinue\'; $root=[IO.Path]::GetFullPath($env:PREFIX).TrimEnd(\'\\\')+\'\\\'; $all=@(Get-CimInstance Win32_Process); $keep=@{}; $id=[int]$PID; while($id -and -not $keep.ContainsKey($id)){ $keep[$id]=1; $id=[int](($all | Where-Object { [int]$_.ProcessId -eq $id } | Select-Object -First 1).ParentProcessId) }; $own=@($all | Where-Object { $_.ExecutablePath -and $_.ExecutablePath.StartsWith($root, [StringComparison]::OrdinalIgnoreCase) -and -not $keep.ContainsKey([int]$_.ProcessId) -and $_.Name -ne \'_conda.exe\' -and $_.Name -notlike \'Uninstall-*\' }); foreach($p in $own){ Write-Output (\'Stopping \' + $p.Name + \' (process \' + $p.ProcessId + \') started from \' + $root); Stop-Process -Id ([int]$p.ProcessId) -Force }; foreach($p in $own){ Wait-Process -Id ([int]$p.ProcessId) -Timeout 15 }; if($own.Count -eq 0){ Write-Output \'No process of the app is running\' }"', + 'REM a file a process uses, so the uninstall left the app folder behind (template 0.1.47). Only programs inside this app folder (the folder', + 'REM of this script) are stopped, never this uninstaller or its helpers; unsaved notebook edits since the last autosave are lost.', + 'SET "LC_APP_ROOT=%~dp0"', + '"%SystemRoot%\\System32\\WindowsPowerShell\\v1.0\\powershell.exe" -NoProfile -ExecutionPolicy Bypass -Command "$ErrorActionPreference=\'SilentlyContinue\'; $root=[IO.Path]::GetFullPath($env:LC_APP_ROOT).TrimEnd(\'\\\')+\'\\\'; Write-Output (\'Stopping the processes started from \' + $root); $all=@(Get-CimInstance Win32_Process); $keep=@{}; $id=[int]$PID; while($id -and -not $keep.ContainsKey($id)){ $keep[$id]=1; $id=[int](($all | Where-Object { [int]$_.ProcessId -eq $id } | Select-Object -First 1).ParentProcessId) }; $own=@($all | Where-Object { $_.ExecutablePath -and $_.ExecutablePath.StartsWith($root, [StringComparison]::OrdinalIgnoreCase) -and -not $keep.ContainsKey([int]$_.ProcessId) -and $_.Name -ne \'_conda.exe\' -and $_.Name -notlike \'Uninstall-*\' }); foreach($p in $own){ Write-Output (\'Stopping \' + $p.Name + \' (process \' + $p.ProcessId + \')\'); Stop-Process -Id ([int]$p.ProcessId) -Force }; foreach($p in $own){ Wait-Process -Id ([int]$p.ProcessId) -Timeout 15 }; if($own.Count -eq 0){ Write-Output \'No process of the app is running\' }" > "%TEMP%\\labconstrictor_pre_uninstall.log" 2>&1', + 'type "%TEMP%\\labconstrictor_pre_uninstall.log"', ) BY_HAND = f"add the lines of STOP_LINES in this migration before the end of the script (see {DOCS_URL})" diff --git a/.tools/docs/migration_0_1_47.md b/.tools/docs/migration_0_1_47.md index 62b4ee6..24ce5d2 100644 --- a/.tools/docs/migration_0_1_47.md +++ b/.tools/docs/migration_0_1_47.md @@ -15,12 +15,14 @@ even after the process ended. ## What changes -`app/bash_bat_scripts/pre_uninstall.bat` now ends with one PowerShell command (after three REM lines) that: +`app/bash_bat_scripts/pre_uninstall.bat` now ends with one PowerShell command (after three REM lines and the app folder, which is the folder of +the script) that: * stops every process whose program is inside the app folder: a Jupyter server and its kernels, a Napari or Fiji tool worker, any other Python of the app; * leaves the uninstaller alone: its own process chain, `_conda.exe` and `Uninstall-*.exe`; -* waits up to 15 s for each process to end. +* waits up to 15 s for each process to end; +* writes what it stopped to `%TEMP%\labconstrictor_pre_uninstall.log`, which the uninstaller also shows. The uninstall then removes the whole folder. Notebook edits made since Jupyter's last autosave (every 2 minutes by default) are lost. The installer round trip checks this on Windows: a running Python of the app is stopped, and the folder is gone. @@ -29,7 +31,7 @@ Linux and macOS do not change: a running process does not stop the removal of it ## What the migration does -It adds the four lines just before the line `echo Pre-uninstall completed!` of `pre_uninstall.bat`, keeping the file's line endings. A +It adds the six lines just before the line `echo Pre-uninstall completed!` of `pre_uninstall.bat`, keeping the file's line endings. A script that already has them is left as it is. So is a script without that line (SKIPPED: add the lines by hand). The change reaches users with the app's next release. diff --git a/app/bash_bat_scripts/pre_uninstall.bat b/app/bash_bat_scripts/pre_uninstall.bat index 67e5af8..c163b8c 100644 --- a/app/bash_bat_scripts/pre_uninstall.bat +++ b/app/bash_bat_scripts/pre_uninstall.bat @@ -6,8 +6,10 @@ IF ERRORLEVEL 1 IF EXIST "%USERPROFILE%\.labconstrictor\apps\PROJECT_NAME.json" SET "ARP_KEY=HKCU\Software\Microsoft\Windows\CurrentVersion\Uninstall\UNDERSCORED_PROJECT_NAME" reg delete "%ARP_KEY%" /f >NUL 2>&1 REM Stop the processes of this app that still run (a Jupyter server and its kernels, a Napari or Fiji tool worker): Windows cannot delete -REM a file a process uses, so the uninstall left the app folder behind (template 0.1.47). Only programs inside this app folder are stopped, -REM never this uninstaller or its own helpers; unsaved notebook edits since the last autosave are lost. -powershell -NoProfile -ExecutionPolicy Bypass -Command "$ErrorActionPreference='SilentlyContinue'; $root=[IO.Path]::GetFullPath($env:PREFIX).TrimEnd('\')+'\'; $all=@(Get-CimInstance Win32_Process); $keep=@{}; $id=[int]$PID; while($id -and -not $keep.ContainsKey($id)){ $keep[$id]=1; $id=[int](($all | Where-Object { [int]$_.ProcessId -eq $id } | Select-Object -First 1).ParentProcessId) }; $own=@($all | Where-Object { $_.ExecutablePath -and $_.ExecutablePath.StartsWith($root, [StringComparison]::OrdinalIgnoreCase) -and -not $keep.ContainsKey([int]$_.ProcessId) -and $_.Name -ne '_conda.exe' -and $_.Name -notlike 'Uninstall-*' }); foreach($p in $own){ Write-Output ('Stopping ' + $p.Name + ' (process ' + $p.ProcessId + ') started from ' + $root); Stop-Process -Id ([int]$p.ProcessId) -Force }; foreach($p in $own){ Wait-Process -Id ([int]$p.ProcessId) -Timeout 15 }; if($own.Count -eq 0){ Write-Output 'No process of the app is running' }" +REM a file a process uses, so the uninstall left the app folder behind (template 0.1.47). Only programs inside this app folder (the folder +REM of this script) are stopped, never this uninstaller or its helpers; unsaved notebook edits since the last autosave are lost. +SET "LC_APP_ROOT=%~dp0" +"%SystemRoot%\System32\WindowsPowerShell\v1.0\powershell.exe" -NoProfile -ExecutionPolicy Bypass -Command "$ErrorActionPreference='SilentlyContinue'; $root=[IO.Path]::GetFullPath($env:LC_APP_ROOT).TrimEnd('\')+'\'; Write-Output ('Stopping the processes started from ' + $root); $all=@(Get-CimInstance Win32_Process); $keep=@{}; $id=[int]$PID; while($id -and -not $keep.ContainsKey($id)){ $keep[$id]=1; $id=[int](($all | Where-Object { [int]$_.ProcessId -eq $id } | Select-Object -First 1).ParentProcessId) }; $own=@($all | Where-Object { $_.ExecutablePath -and $_.ExecutablePath.StartsWith($root, [StringComparison]::OrdinalIgnoreCase) -and -not $keep.ContainsKey([int]$_.ProcessId) -and $_.Name -ne '_conda.exe' -and $_.Name -notlike 'Uninstall-*' }); foreach($p in $own){ Write-Output ('Stopping ' + $p.Name + ' (process ' + $p.ProcessId + ')'); Stop-Process -Id ([int]$p.ProcessId) -Force }; foreach($p in $own){ Wait-Process -Id ([int]$p.ProcessId) -Timeout 15 }; if($own.Count -eq 0){ Write-Output 'No process of the app is running' }" > "%TEMP%\labconstrictor_pre_uninstall.log" 2>&1 +type "%TEMP%\labconstrictor_pre_uninstall.log" echo Pre-uninstall completed! SetLocal EnableDelayedExpansion diff --git a/tests/smoke/installer_roundtrip.py b/tests/smoke/installer_roundtrip.py index e280b48..76199f4 100644 --- a/tests/smoke/installer_roundtrip.py +++ b/tests/smoke/installer_roundtrip.py @@ -224,7 +224,13 @@ def main() -> int: try: uninstall(prefix, env) if busy is not None: + log = Path(os.environ.get("TEMP", ".")) / "labconstrictor_pre_uninstall.log" + print(f"--- {log}:\n{tail(log)}", flush=True) + if log.is_file(): + shutil.copyfile(log, args.logs / "pre_uninstall_busy.log") if busy.poll() is None: + for line in leftovers(prefix): + print(line, flush=True) raise AssertionError(f"the uninstall did not stop the app's running process {busy.pid}") ok(f"the uninstall stopped the app's running process {busy.pid}") check_uninstalled(prefix, env, other) diff --git a/tests/test_template_sync_0_1_47.py b/tests/test_template_sync_0_1_47.py index adfb036..a12ab01 100644 --- a/tests/test_template_sync_0_1_47.py +++ b/tests/test_template_sync_0_1_47.py @@ -50,14 +50,16 @@ def test_the_lines_come_once_just_before_the_last_message(self) -> None: self.assertEqual(sum(line == MIGRATION.STOP_LINES[0] for line in lines), 1) def test_the_command_survives_cmd_and_spares_the_uninstaller(self) -> None: - command = MIGRATION.STOP_LINES[-1] - self.assertTrue(command.startswith("powershell -NoProfile -ExecutionPolicy Bypass -Command \"")) - self.assertTrue(command.endswith('"')) - self.assertEqual(command.count('"'), 2, "one quoted argument: cmd passes it whole") + command = next(line for line in MIGRATION.STOP_LINES if "powershell.exe" in line) + self.assertTrue(command.startswith('"%SystemRoot%\\System32\\WindowsPowerShell\\v1.0\\powershell.exe" -NoProfile -ExecutionPolicy Bypass -Command "')) + script = command.split(' -Command "', 1)[1].rsplit('" > ', 1)[0] + self.assertNotIn('"', script, "one quoted argument: cmd passes it whole") for character in ("%", "!"): - self.assertNotIn(character, command, "cmd would expand it") - for spared in ("$keep", "'_conda.exe'", "'Uninstall-*'", "$env:PREFIX", "StartsWith($root"): - self.assertIn(spared, command) + self.assertNotIn(character, script, "cmd would expand it") + for spared in ("$keep", "'_conda.exe'", "'Uninstall-*'", "$env:LC_APP_ROOT", "StartsWith($root"): + self.assertIn(spared, script) + self.assertIn('SET "LC_APP_ROOT=%~dp0"', MIGRATION.STOP_LINES, "the app folder is the folder of pre_uninstall.bat") + self.assertTrue(command.endswith('> "%TEMP%\\labconstrictor_pre_uninstall.log" 2>&1')) for name in ("UNDERSCORED_PROJECT_NAME", "PROJECT_NAME", "BASE_PATH"): self.assertNotIn(name, "".join(MIGRATION.STOP_LINES), "no placeholder: the lines are the same in every app")