diff --git a/.github/workflows/build-qt-linux.yml b/.github/workflows/build-qt-linux.yml index bfc793ce8..b030258d7 100644 --- a/.github/workflows/build-qt-linux.yml +++ b/.github/workflows/build-qt-linux.yml @@ -114,7 +114,7 @@ jobs: libxcb-keysyms1 libxcb-render-util0 libxcb-xinerama0 libxcb-xkb1 \ libxcb-shape0 libxcb-randr0 libxcb-sync1 libxcb-xfixes0 libxcb-glx0 \ libwayland-client0 libwayland-egl1 libwayland-cursor0 libegl1 libgl1 \ - patchelf file binutils + patchelf file binutils dbus-daemon # Official Qt binaries — WITHOUT qtshadertools: with qsb on PATH build.rs # re-bakes shaders by mtime and a fresh checkout is nondeterministic. @@ -239,29 +239,22 @@ jobs: test -f AppDir/usr/share/licenses/qbz/third-party/Apache-2.0-dst-decoder.txt du -sh AppDir - # THE gate. Runs the AppDir with the Qt install removed from the - # environment so a missing plugin/module cannot be masked by the build - # box. Pass = the app booted (>= 10 log lines), reached core init, and - # the QML engine logged no complaint. `home published` is NOT required: - # it needs a logged-in session and CI has none — the boot stops at the - # login screen, which is the point this gate proves reachable. + # The shipped AppDir must initialize AND survive the observation window. + # Hide the SDK and use a fresh profile/private bus; early exit (even 0) + # fails. The helper reaps the launcher and its private process group. - name: Offscreen smoke (the AppDir that ships) run: | - set -uo pipefail - env -u LD_LIBRARY_PATH -u QT_PLUGIN_PATH -u QML_IMPORT_PATH -u QML2_IMPORT_PATH \ - QT_QPA_PLATFORM=offscreen RUST_LOG=info \ - timeout 60 ./AppDir/AppRun > smoke.log 2>&1 || true - lines=$(wc -l < smoke.log) - echo "smoke log: $lines lines" - if (( lines < 10 )); then cat smoke.log; echo "::error::the app did not start"; exit 1; fi - errs=$(grep -av 'propertyCache' smoke.log \ - | grep -aciE 'is not a type|unavailable|ReferenceError|TypeError|Cannot read|Unable to assign|Cannot open|no such method|non-existent property|failed to load component|is not installed' || true) - if (( errs > 0 )); then - grep -av 'propertyCache' smoke.log | grep -aiE 'is not a type|unavailable|ReferenceError|TypeError|Cannot read|Unable to assign|Cannot open|no such method|non-existent property|failed to load component|is not installed' | head -20 - echo "::error::$errs QML complaint(s) in the smoke log"; exit 1 - fi - grep -aq 'QbzCore initialized' smoke.log || { tail -20 smoke.log; echo "::error::never reached QbzCore init"; exit 1; } - echo "smoke OK (0 QML complaints, core initialized)" + python3 scripts/packaging/smoke_release.py ./AppDir/AppRun \ + --hide-qt "$QT_ROOT_DIR" --seconds 60 --log smoke.log + + - name: Upload deployed startup evidence + if: always() + uses: actions/upload-artifact@v7 + with: + name: qbz-appdir-smoke-${{ inputs.arch }} + path: smoke.log* + if-no-files-found: ignore + retention-days: 14 - name: Upload bare binary uses: actions/upload-artifact@v7 diff --git a/.github/workflows/release-flatpak.yml b/.github/workflows/release-flatpak.yml index 92e6d0788..825345bc3 100644 --- a/.github/workflows/release-flatpak.yml +++ b/.github/workflows/release-flatpak.yml @@ -150,7 +150,7 @@ jobs: - name: Install flatpak tooling run: | sudo apt-get update - sudo apt-get install -y flatpak flatpak-builder + sudo apt-get install -y flatpak flatpak-builder dbus-daemon flatpak remote-add --user --if-not-exists flathub https://flathub.org/repo/flathub.flatpakrepo - name: Install runtimes @@ -175,20 +175,24 @@ jobs: echo "bundle_name=${BUNDLE_NAME}" >> "$GITHUB_OUTPUT" ls -la dist - # The bundle must boot on the KDE runtime's Qt: same offscreen gate as - # the Linux AppDir, run inside the sandbox. + # Observe flatpak run until the deadline, with a fresh sandbox profile + # and private bus. A crash/early exit after core init must still fail. - name: Offscreen smoke (inside the sandbox) run: | - set -uo pipefail + set -euo pipefail flatpak install --user -y --noninteractive --bundle "dist/${{ steps.build_flatpak.outputs.bundle_name }}" || \ flatpak install --user -y --noninteractive "dist/${{ steps.build_flatpak.outputs.bundle_name }}" - timeout 60 flatpak run --env=QT_QPA_PLATFORM=offscreen --env=RUST_LOG=info com.blitzfc.qbz > smoke.log 2>&1 || true - lines=$(wc -l < smoke.log); echo "smoke log: $lines lines" - if (( lines < 10 )); then cat smoke.log; echo "::error::the app did not start"; exit 1; fi - errs=$(grep -av 'propertyCache' smoke.log | grep -aciE 'is not a type|unavailable|ReferenceError|TypeError|Cannot read|Unable to assign|Cannot open|no such method|non-existent property|failed to load component|is not installed' || true) - if (( errs > 0 )); then grep -av 'propertyCache' smoke.log | grep -aiE 'is not a type|unavailable|ReferenceError|TypeError|Cannot read|Unable to assign|Cannot open|no such method|non-existent property|failed to load component|is not installed' | head -20; echo "::error::$errs QML complaint(s)"; exit 1; fi - grep -aq 'QbzCore initialized' smoke.log || { tail -20 smoke.log; echo "::error::never reached QbzCore init"; exit 1; } - echo "smoke OK" + python3 scripts/packaging/smoke_release.py com.blitzfc.qbz \ + --flatpak --seconds 60 --log smoke.log + + - name: Upload deployed startup evidence + if: always() + uses: actions/upload-artifact@v7 + with: + name: qbz-flatpak-smoke + path: smoke.log* + if-no-files-found: ignore + retention-days: 14 - name: Upload Flatpak bundle uses: actions/upload-artifact@v7 diff --git a/.github/workflows/release-macos.yml b/.github/workflows/release-macos.yml index ed34ebf3e..556890646 100644 --- a/.github/workflows/release-macos.yml +++ b/.github/workflows/release-macos.yml @@ -263,30 +263,25 @@ jobs: cp "$QT_ROOT_DIR/plugins/platforms/libqoffscreen.dylib" "$APP/Contents/PlugIns/platforms/" du -sh "$APP" - # THE gate: the bundle boots without the Qt install. Pass = >= 10 log - # lines, zero QML complaints, core initialized (login screen reached; - # `home published` needs a session CI does not have). + # The bundle must initialize AND survive without the Qt SDK. The helper + # uses a private native macOS home (XDG alone is ineffective), restores + # the SDK on failure/cancellation and reaps the observed process group. - name: Offscreen smoke (the bundle that ships) run: | - set -uo pipefail + set -euo pipefail APP="dist/QBZ.app" - mv "$QT_ROOT_DIR" "${QT_ROOT_DIR}.hidden" - ( env -u DYLD_LIBRARY_PATH -u DYLD_FRAMEWORK_PATH -u QT_PLUGIN_PATH -u QML_IMPORT_PATH -u QML2_IMPORT_PATH \ - QT_QPA_PLATFORM=offscreen RUST_LOG=info "$APP/Contents/MacOS/qbz" > smoke.log 2>&1 & echo $! > smoke.pid ) - sleep 45; kill "$(cat smoke.pid)" 2>/dev/null || true; sleep 1 - mv "${QT_ROOT_DIR}.hidden" "$QT_ROOT_DIR" - lines=$(wc -l < smoke.log | tr -d ' ') - echo "smoke log: $lines lines" - if (( lines < 10 )); then cat smoke.log; echo "::error::the app did not start"; exit 1; fi - errs=$(grep -av 'propertyCache' smoke.log \ - | grep -aciE 'is not a type|unavailable|ReferenceError|TypeError|Cannot read|Unable to assign|Cannot open|no such method|non-existent property|failed to load component|is not installed|Library not loaded|dyld' || true) - if (( errs > 0 )); then - grep -av 'propertyCache' smoke.log | grep -aiE 'is not a type|unavailable|ReferenceError|TypeError|Cannot read|Unable to assign|Cannot open|no such method|non-existent property|failed to load component|is not installed|Library not loaded|dyld' | head -20 - echo "::error::$errs QML/loader complaint(s) in the smoke log"; exit 1 - fi - grep -aq 'QbzCore initialized' smoke.log || { tail -20 smoke.log; echo "::error::never reached QbzCore init"; exit 1; } + python3 scripts/packaging/smoke_release.py "$APP/Contents/MacOS/qbz" \ + --hide-qt "$QT_ROOT_DIR" --seconds 45 --log smoke.log rm -f "$APP/Contents/PlugIns/platforms/libqoffscreen.dylib" - echo "smoke OK (0 QML complaints, core initialized)" + + - name: Upload deployed startup evidence + if: always() + uses: actions/upload-artifact@v7 + with: + name: qbz-macos-smoke-${{ matrix.arch }} + path: smoke.log* + if-no-files-found: ignore + retention-days: 14 # Ad-hoc signature: required for arm64 Macs to launch at all. AFTER # macdeployqt (it rewrites install names) and after the smoke plugin diff --git a/.github/workflows/test-crates.yml b/.github/workflows/test-crates.yml index 0b3ab08e8..90ea53a2c 100644 --- a/.github/workflows/test-crates.yml +++ b/.github/workflows/test-crates.yml @@ -45,6 +45,8 @@ on: - "scripts/test_qt_build_gates.py" - "scripts/packaging/windows_crt.py" - "scripts/packaging/test_windows_crt.py" + - "scripts/packaging/smoke_release.py" + - "scripts/packaging/test_smoke_release.py" - "scripts/qml-audits/**" - ".github/workflows/test-crates.yml" push: @@ -58,6 +60,8 @@ on: - "scripts/test_qt_build_gates.py" - "scripts/packaging/windows_crt.py" - "scripts/packaging/test_windows_crt.py" + - "scripts/packaging/smoke_release.py" + - "scripts/packaging/test_smoke_release.py" - "scripts/qml-audits/**" - ".github/workflows/test-crates.yml" workflow_dispatch: diff --git a/scripts/cargo-test.sh b/scripts/cargo-test.sh index 5eafe539b..5b3092316 100755 --- a/scripts/cargo-test.sh +++ b/scripts/cargo-test.sh @@ -53,6 +53,9 @@ python3 scripts/test_qt_build_gates.py say "gate: Windows app-local CRT import regressions" python3 scripts/packaging/test_windows_crt.py +say "gate: packaged Qt process survival and smoke isolation" +python3 scripts/packaging/test_smoke_release.py + say "gate: all eight gettext catalogs" for locale in en es de fr pt ru ja nl; do msgfmt --check --output-file=/dev/null "crates/qbz-i18n/translations/$locale/LC_MESSAGES/qbz-ui.po" diff --git a/scripts/packaging/smoke_release.py b/scripts/packaging/smoke_release.py new file mode 100644 index 000000000..aabf4c728 --- /dev/null +++ b/scripts/packaging/smoke_release.py @@ -0,0 +1,254 @@ +#!/usr/bin/env python3 +"""Observe a deployed Linux/macOS product, including early exit and cleanup. + +AppRun and Flatpak remain the launchers under test. macOS runs the deployed +bundle executable. These are startup checks, without a session or playback; +offscreen rendering does not certify a physical display or audio device. +""" + +import argparse +import contextlib +import importlib.util +import json +import os +from pathlib import Path +import re +import resource +import selectors +import shutil +import signal +import subprocess +import sys +import tempfile +import time +import uuid +from xml.sax.saxutils import escape + +sys.dont_write_bytecode = True +_spec = importlib.util.spec_from_file_location( + "qt_smoke", Path(__file__).resolve().parents[1] / "qt-smoke.py") +_startup = importlib.util.module_from_spec(_spec) +_spec.loader.exec_module(_startup) + +# Keep the existing startup/log contract, including its propertyCache exception. +LOADER_ERROR = re.compile(r"Library not loaded|dyld:|This application failed to start", re.I) +UNSET = ( + "LD_LIBRARY_PATH", "DYLD_LIBRARY_PATH", "DYLD_FRAMEWORK_PATH", + "DYLD_FALLBACK_LIBRARY_PATH", "DYLD_FALLBACK_FRAMEWORK_PATH", + "QT_PLUGIN_PATH", "QML_IMPORT_PATH", "QML2_IMPORT_PATH", "QT_ROOT_DIR", + "QTDIR", "QMAKE", "QT_QPA_PLATFORM_PLUGIN_PATH", "QT_QPA_PLATFORM", + "DISPLAY", "WAYLAND_DISPLAY", "DBUS_SESSION_BUS_ADDRESS", "DBUS_SESSION_BUS_PID", + "QBZ_RENDERER", "QT_QUICK_BACKEND", "QSG_RHI_BACKEND", "QT_SCALE_FACTOR", + "QBZ_PROFILE", +) +PROFILE_DIRS = { + "HOME": "home", "XDG_CONFIG_HOME": "config", "XDG_DATA_HOME": "data", + "XDG_CACHE_HOME": "cache", "XDG_STATE_HOME": "state", "XDG_RUNTIME_DIR": "run", +} + + +def isolated_environment(root, original, platform): + env = {name: value for name, value in original.items() if name not in UNSET} + for name, folder in PROFILE_DIRS.items(): + path = root / folder + path.mkdir(mode=0o700, parents=True, exist_ok=True) + env[name] = str(path) + if platform == "darwin": + # dirs::{data,config,cache}_dir use HOME/Library on macOS, not XDG. + # CoreFoundation/Qt also get the private home; the shell's home is unchanged. + env["CFFIXED_USER_HOME"] = env["HOME"] + for folder in ("Application Support", "Caches", "Preferences"): + (Path(env["HOME"]) / "Library" / folder).mkdir(parents=True, mode=0o700) + env.update(PATH="/usr/bin:/bin:/usr/sbin:/sbin", QT_QPA_PLATFORM="offscreen", RUST_LOG="info") + return env + + +def no_core_dump(): + # Child-only limit: injected crashes must not write cores in the checkout. + resource.setrlimit(resource.RLIMIT_CORE, (0, 0)) + + +def signal_group(process, sig): + try: + os.killpg(process.pid, sig) + except ProcessLookupError: + pass + + +def stop_group(process, grace=3): + """Always reap the launcher; also kill descendants if it exits first.""" + signal_group(process, signal.SIGTERM) + try: + process.wait(timeout=grace) + except subprocess.TimeoutExpired: + pass + finally: + # A wrapper may have exited while a child ignored SIGTERM. Checking + # only process.poll() here would leak that child. + signal_group(process, signal.SIGKILL) + process.wait(timeout=3) + + +def observe(command, env, seconds, log, grace=3): + if seconds <= 0: + raise RuntimeError("observation window must be positive") + started = time.monotonic() + survived = False + with Path(log).open("wb") as output: + process = subprocess.Popen(command, env=env, stdout=output, + stderr=subprocess.STDOUT, start_new_session=True, + preexec_fn=no_core_dump) + try: + try: + process.wait(timeout=seconds) + except subprocess.TimeoutExpired: + survived = process.poll() is None + finally: + # An exit immediately after the deadline is still an application + # exit, not a shutdown we initiated. Preserve its actual status. + if process.poll() is not None: + survived = False + observed_seconds = time.monotonic() - started + stop_group(process, grace) + result = {"command": command, "pid": process.pid, "survived": survived, + "observed_seconds": observed_seconds, "returncode": process.returncode} + Path(str(log) + ".json").write_text(json.dumps(result, indent=2) + "\n") + output = Path(log).read_text(errors="replace") + _startup.check_result(output, survived, process.returncode) + if LOADER_ERROR.search(output): + raise RuntimeError("loader complaints in deployed product log") + return result + + +@contextlib.contextmanager +def private_bus(root, env, log): + daemon = shutil.which("dbus-daemon", path=env["PATH"]) + if daemon is None: + raise RuntimeError("dbus-daemon is required for an isolated Linux smoke") + # No service directories: a private bus must not activate the runner's + # portals/keyring/desktop helpers outside the process group we own. + config = root / "bus.conf" + config.write_text('sessionEXTERNAL' + '' + escape("unix:path=" + str(root / "bus")) + '' + '' + '' + '') + with Path(str(log) + ".dbus").open("wb") as output: + process = subprocess.Popen( + [daemon, "--config-file=" + str(config), "--nofork", "--nopidfile", "--print-address=1"], + env=env, stdout=subprocess.PIPE, stderr=output, start_new_session=True) + try: + with selectors.DefaultSelector() as selector: + selector.register(process.stdout, selectors.EVENT_READ) + if not selector.select(5): + raise RuntimeError("private D-Bus did not publish its address") + address = process.stdout.readline().decode().strip() + if not address.startswith("unix:") or process.poll() is not None: + raise RuntimeError("private D-Bus failed to start") + yield address + finally: + stop_group(process) + process.stdout.close() + + +@contextlib.contextmanager +def hidden_sdk(path): + if path is None: + yield + return + source = Path(path).resolve(strict=True) + if not source.is_dir() or source == Path(source.anchor): + raise RuntimeError("Qt SDK path must name its installation directory") + hidden = source.with_name(source.name + ".qbz-smoke-hidden-" + uuid.uuid4().hex) + source.rename(hidden) + try: + yield + finally: + hidden.rename(source) + + +@contextlib.contextmanager +def cleanup_on_signal(): + def interrupt(signum, _frame): + # Allow finally blocks to finish even if cancellation sends another signal. + for sig in (signal.SIGINT, signal.SIGTERM): + signal.signal(sig, signal.SIG_IGN) + raise RuntimeError(f"smoke interrupted by signal {signum}") + + previous = {sig: signal.signal(sig, interrupt) for sig in (signal.SIGINT, signal.SIGTERM)} + try: + yield + finally: + for sig, handler in previous.items(): + signal.signal(sig, handler) + + +def flatpak_command(app, env, original, root): + flatpak = shutil.which("flatpak", path=env["PATH"]) + if not flatpak: + raise RuntimeError("flatpak is required") + host_env = dict(env) + # The CLI must find the installation made by `flatpak install --user`. + # Only the sandboxed product gets a fresh profile; the bus remains private. + for name in ("HOME", "XDG_DATA_HOME", "XDG_CONFIG_HOME"): + if name in original: + host_env[name] = original[name] + else: + host_env.pop(name, None) + # Flatpak has its own /tmp. No extra filesystem permission is granted. + sandbox_root = Path("/tmp") / root.name + command = [flatpak, "run", "--user", "--die-with-parent", "--no-a11y-bus"] + command.extend("--unset-env=" + name for name in UNSET + if name not in ("DBUS_SESSION_BUS_ADDRESS", "DBUS_SESSION_BUS_PID")) + command.extend("--env=" + name + "=" + str(sandbox_root / folder) + for name, folder in PROFILE_DIRS.items()) + command.extend(["--env=QT_QPA_PLATFORM=offscreen", "--env=RUST_LOG=info", + "--command=sh", app, "-c", + 'set -eu; umask 077; mkdir -p "$HOME" "$XDG_CONFIG_HOME" "$XDG_DATA_HOME" ' + '"$XDG_CACHE_HOME" "$XDG_STATE_HOME" "$XDG_RUNTIME_DIR"; ' + 'exec /app/bin/qbz']) + return command, host_env + + +def smoke(target, seconds, log, *, flatpak=False, qt_sdk=None): + if sys.platform != "darwin" and not sys.platform.startswith("linux"): + raise RuntimeError("deployed smoke supports Linux and macOS only") + if flatpak and not sys.platform.startswith("linux"): + raise RuntimeError("Flatpak smoke requires Linux") + log = Path(log).resolve() + command = None if flatpak else [str(Path(target).absolute())] + with cleanup_on_signal(), contextlib.ExitStack() as stack: + directory = stack.enter_context(tempfile.TemporaryDirectory(prefix="qbz-release-smoke-")) + root = Path(directory) + original = dict(os.environ) + env = isolated_environment(root, original, sys.platform) + if sys.platform.startswith("linux"): + env["DBUS_SESSION_BUS_ADDRESS"] = stack.enter_context(private_bus(root, env, log)) + if flatpak: + command, env = flatpak_command(target, env, original, root) + stack.enter_context(hidden_sdk(qt_sdk)) + return observe(command, env, seconds, log) + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("target", help="deployed executable/AppRun, or Flatpak app id") + parser.add_argument("--flatpak", action="store_true") + parser.add_argument("--hide-qt", type=Path, help="temporarily hide this SDK; restored even on failure") + parser.add_argument("--seconds", type=float, default=60) + parser.add_argument("--log", required=True, type=Path) + args = parser.parse_args() + try: + result = smoke(args.target, args.seconds, args.log, flatpak=args.flatpak, qt_sdk=args.hide_qt) + except (OSError, RuntimeError, subprocess.SubprocessError) as error: + if args.log.is_file(): + print("\n".join(args.log.read_text(errors="replace").splitlines()[-30:]), file=sys.stderr) + print(f"deployed smoke FAILED: {error}", file=sys.stderr) + return 1 + print(f"deployed smoke OK: core initialized, survived {result['observed_seconds']:.1f}s; " + f"launcher reaped (status {result['returncode']}) — {args.log}") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/scripts/packaging/test_smoke_release.py b/scripts/packaging/test_smoke_release.py new file mode 100644 index 000000000..7a6eaa158 --- /dev/null +++ b/scripts/packaging/test_smoke_release.py @@ -0,0 +1,219 @@ +#!/usr/bin/env python3 +"""Real subprocess regressions for the release startup gate; no Qt/build required.""" + +import importlib.util +import json +import os +from pathlib import Path +import signal +import subprocess +import sys +import tempfile +import time +import unittest +from unittest.mock import patch + +sys.dont_write_bytecode = True +spec = importlib.util.spec_from_file_location("smoke_release", Path(__file__).with_name("smoke_release.py")) +smoke = importlib.util.module_from_spec(spec) +spec.loader.exec_module(smoke) + +STARTUP = 'print("QbzCore initialized\\n" + "normal startup log\\n" * 10, flush=True)\n' + + +@unittest.skipUnless(os.name == "posix", "release helper targets Linux/macOS") +class ProcessTests(unittest.TestCase): + def setUp(self): + self.directory = tempfile.TemporaryDirectory(prefix="qbz-release-smoke-test-") + self.addCleanup(self.directory.cleanup) + self.root = Path(self.directory.name) + self.log = self.root / "smoke.log" + + def run_fake(self, code, seconds=.25): + return smoke.observe([sys.executable, "-u", "-c", code], dict(os.environ), + seconds, self.log, grace=.15) + + def assert_reaped(self, pid): + with self.assertRaises(ProcessLookupError): + os.kill(pid, 0) + with self.assertRaises(ChildProcessError): + os.waitpid(pid, os.WNOHANG) + + def test_core_then_exit_zero_is_rejected_and_reaped(self): + with self.assertRaisesRegex(RuntimeError, "exited before"): + self.run_fake(STARTUP) + result = json.loads(Path(str(self.log) + ".json").read_text()) + self.assertEqual(result["returncode"], 0) + self.assert_reaped(result["pid"]) + + def test_core_then_signal_crash_is_rejected_without_core_dump(self): + with self.assertRaisesRegex(RuntimeError, "exited before"): + self.run_fake(STARTUP + 'import os, resource, signal\n' + 'assert resource.getrlimit(resource.RLIMIT_CORE) == (0, 0)\n' + 'os.kill(os.getpid(), signal.SIGSEGV)\n') + result = json.loads(Path(str(self.log) + ".json").read_text()) + self.assertEqual(result["returncode"], -signal.SIGSEGV) + self.assert_reaped(result["pid"]) + + def test_wrapper_cannot_hide_early_child_exit(self): + # AppRun/flatpak may propagate a child's status via a waiting wrapper. + # Even a wrapper that maps that status to 0 must not pass early. + for status in ("0", "7"): + with self.subTest(status=status), self.assertRaisesRegex(RuntimeError, "exited before"): + child = STARTUP + "raise SystemExit(" + status + ")\n" + self.run_fake('import subprocess, sys\n' + f'subprocess.run([sys.executable, "-u", "-c", {child!r}])\n') + + def test_live_process_is_accepted_and_reaped(self): + result = self.run_fake(STARTUP + "import time; time.sleep(60)\n") + self.assertTrue(result["survived"]) + self.assertGreaterEqual(result["observed_seconds"], .25) + self.assertEqual(result["returncode"], -signal.SIGTERM) + self.assert_reaped(result["pid"]) + + def test_live_process_ignoring_term_is_killed_and_reaped(self): + result = self.run_fake('import signal, time\n' + 'signal.signal(signal.SIGTERM, signal.SIG_IGN)\n' + + STARTUP + 'time.sleep(60)\n') + self.assertEqual(result["returncode"], -signal.SIGKILL) + self.assert_reaped(result["pid"]) + + def test_waiting_wrapper_and_its_child_are_stopped(self): + code = ('import subprocess, sys, signal, time\n' + 'child = subprocess.Popen([sys.executable, "-c", "import time; time.sleep(60)"])\n' + 'def stop(sig, frame):\n' + ' child.wait(timeout=2)\n' + ' raise SystemExit(0)\n' + 'signal.signal(signal.SIGTERM, stop)\n' + 'print("child=" + str(child.pid), flush=True)\n' + STARTUP + 'time.sleep(60)\n') + result = self.run_fake(code) + child = int(self.log.read_text().splitlines()[0].split("=", 1)[1]) + self.assert_reaped(result["pid"]) + with self.assertRaises(ProcessLookupError): + os.kill(child, 0) + + def test_alive_without_core_or_with_qml_errors_still_fails(self): + for logs in ('print("log\\n" * 12, flush=True)\n', + STARTUP + 'print("ReferenceError: missing", flush=True)\n'): + with self.subTest(logs=logs), self.assertRaises(RuntimeError): + self.run_fake(logs + 'import time; time.sleep(60)\n') + result = json.loads(Path(str(self.log) + ".json").read_text()) + self.assertTrue(result["survived"]) + self.assert_reaped(result["pid"]) + + def test_sdk_is_hidden_and_restored_after_gate_failure(self): + sdk = self.root / "Qt SDK" + sdk.mkdir() + (sdk / "marker").write_text("original") + with self.assertRaisesRegex(RuntimeError, "exited before"): + with smoke.hidden_sdk(sdk): + self.assertFalse(sdk.exists()) + self.run_fake(STARTUP) + self.assertEqual((sdk / "marker").read_text(), "original") + self.assertEqual(list(self.root.glob("*.qbz-smoke-hidden-*")), []) + + def test_spawn_failure_also_restores_sdk(self): + sdk = self.root / "Qt" + sdk.mkdir() + with self.assertRaises(FileNotFoundError): + with smoke.hidden_sdk(sdk): + smoke.observe([str(self.root / "missing")], {}, .1, self.log) + self.assertTrue(sdk.is_dir()) + + @unittest.skipUnless(sys.platform.startswith("linux"), "Linux private D-Bus fixture") + def test_complete_gate_has_private_bus_profile_and_reaps_after_failure(self): + fake = self.root / "qbz" + fake.write_text('#!' + sys.executable + '\nimport json, os\n' + STARTUP + + 'print(json.dumps({name: os.environ[name] for name in ' + '["HOME", "XDG_DATA_HOME", "DBUS_SESSION_BUS_ADDRESS"]}), flush=True)\n') + fake.chmod(0o755) + original_home = os.environ.get("HOME") + with self.assertRaisesRegex(RuntimeError, "exited before"): + smoke.smoke(fake, .25, self.log) + snapshot = json.loads(self.log.read_text().splitlines()[-1]) + self.assertNotEqual(snapshot["HOME"], original_home) + self.assertIn("qbz-release-smoke-", snapshot["HOME"]) + root = Path(snapshot["HOME"]).parent + self.assertIn(str(root), snapshot["DBUS_SESSION_BUS_ADDRESS"]) + self.assertFalse(root.exists()) + self.assertEqual(os.environ.get("HOME"), original_home) + + def test_cancellation_restores_sdk_and_cleans_observed_process(self): + # Exercise the CLI's SIGTERM handler, not a mocked finally block. + sdk = self.root / "Qt" + sdk.mkdir() + fake = self.root / "qbz" + fake.write_text('#!' + sys.executable + '\nimport os, time\n' + STARTUP + + 'print("product_pid=" + str(os.getpid()), flush=True)\ntime.sleep(60)\n') + fake.chmod(0o755) + gate = subprocess.Popen([sys.executable, str(Path(smoke.__file__)), str(fake), + "--hide-qt", str(sdk), "--seconds", "60", "--log", str(self.log)], + stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True) + try: + deadline = time.monotonic() + 5 + while time.monotonic() < deadline: + if self.log.exists() and "product_pid=" in self.log.read_text(): + break + if gate.poll() is not None: + self.fail(gate.communicate(timeout=2)[0]) + time.sleep(.025) + else: + self.fail("fake product did not start") + self.assertFalse(sdk.exists()) + pid = int(self.log.read_text().split("product_pid=", 1)[1].strip()) + gate.terminate() + output, _ = gate.communicate(timeout=10) + self.assertEqual(gate.returncode, 1, output) + self.assertIn("interrupted by signal", output) + self.assertTrue(sdk.is_dir()) + with self.assertRaises(ProcessLookupError): + os.kill(pid, 0) + finally: + if gate.poll() is None: + gate.kill() + gate.communicate(timeout=5) + + +class EnvironmentTests(unittest.TestCase): + def test_native_macos_home_and_sdk_overrides_are_isolated(self): + with tempfile.TemporaryDirectory() as directory: + root = Path(directory) + original = {"HOME": "/personal", "PATH": "/SDK/bin:/usr/bin", + "CFFIXED_USER_HOME": "/personal", "QT_ROOT_DIR": "/SDK", + "DYLD_FRAMEWORK_PATH": "/SDK/lib", "QML_IMPORT_PATH": "/SDK/qml", + "DBUS_SESSION_BUS_ADDRESS": "unix:path=/personal/bus", + "QBZ_RENDERER": "software", "XDG_DATA_HOME": "/personal/data"} + env = smoke.isolated_environment(root, original, "darwin") + self.assertEqual(original["HOME"], "/personal") + self.assertEqual(env["HOME"], str(root / "home")) + self.assertEqual(env["CFFIXED_USER_HOME"], env["HOME"]) + self.assertTrue((root / "home/Library/Application Support").is_dir()) + self.assertTrue((root / "home/Library/Caches").is_dir()) + self.assertEqual(env["QT_QPA_PLATFORM"], "offscreen") + self.assertNotIn("SDK", env["PATH"]) + for name in ("QT_ROOT_DIR", "DYLD_FRAMEWORK_PATH", "QML_IMPORT_PATH", + "DBUS_SESSION_BUS_ADDRESS", "QBZ_RENDERER"): + self.assertNotIn(name, env) + + def test_flatpak_finds_user_install_but_product_uses_sandbox_profile(self): + with tempfile.TemporaryDirectory(prefix="qbz-release-smoke-") as directory: + root = Path(directory) + original = {"HOME": "/runner", "XDG_DATA_HOME": "/runner/data", + "XDG_CONFIG_HOME": "/runner/config"} + env = smoke.isolated_environment(root, original, "linux") + env["DBUS_SESSION_BUS_ADDRESS"] = "unix:path=" + str(root / "bus") + with patch.object(smoke.shutil, "which", return_value="/usr/bin/flatpak"): + command, host_env = smoke.flatpak_command("com.blitzfc.qbz", env, original, root) + self.assertEqual(host_env["HOME"], "/runner") + self.assertEqual(host_env["XDG_DATA_HOME"], "/runner/data") + self.assertEqual(host_env["DBUS_SESSION_BUS_ADDRESS"], env["DBUS_SESSION_BUS_ADDRESS"]) + self.assertIn("--die-with-parent", command) + self.assertIn("--env=HOME=/tmp/" + root.name + "/home", command) + self.assertIn("--env=XDG_DATA_HOME=/tmp/" + root.name + "/data", command) + self.assertIn("--unset-env=QML_IMPORT_PATH", command) + self.assertFalse(any(arg.startswith("--filesystem=") for arg in command)) + self.assertTrue(command[-1].endswith("exec /app/bin/qbz")) + + +if __name__ == "__main__": + unittest.main()