diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 532576f2f..9f8f9e5cd 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -62,20 +62,20 @@ jobs: coverage: false # Keep exact Rich output and real prompt_toolkit pipes in a fresh # CLI process: long-lived workers can exceed select()'s fd limit. - pytest_args: "-n auto --dist loadfile --ignore=tests/cli/test_commands.py --ignore=tests/cli/test_cli_input.py --ignore=tests/cli/test_desktop_target.py --ignore=tests/cli/test_desktop_target_entrypoints.py" + pytest_args: "-n 4 --dist loadfile --ignore=tests/cli/test_commands.py --ignore=tests/cli/test_cli_input.py --ignore=tests/cli/test_desktop_target.py --ignore=tests/cli/test_desktop_target_entrypoints.py" - name: latest, 3.14 + coverage os: ubuntu-latest python-version: "3.14" coverage: true - pytest_args: "-n auto --dist loadfile --ignore=tests/cli/test_commands.py --ignore=tests/cli/test_cli_input.py --ignore=tests/cli/test_desktop_target.py --ignore=tests/cli/test_desktop_target_entrypoints.py" + pytest_args: "-n 4 --dist loadfile --ignore=tests/cli/test_commands.py --ignore=tests/cli/test_cli_input.py --ignore=tests/cli/test_desktop_target.py --ignore=tests/cli/test_desktop_target_entrypoints.py" - name: Windows, 3.14 os: windows-latest python-version: "3.14" coverage: false # Process identities run serially; isolated update jobs use case-level # scheduling below so one file cannot serialize all real venv work. - # Retain main's three-worker budget and the separate native-process job. - pytest_args: "-n 3 --dist loadfile --ignore=tests/cli/test_commands.py --ignore=tests/cli/test_cli_input.py --ignore=tests/cli/test_desktop_target.py --ignore=tests/cli/test_desktop_target_entrypoints.py --ignore=tests/tools/test_exec_platform.py --ignore=tests/cli/test_wsl_browser.py --ignore=tests/test_install_scripts.py --ignore=tests/test_update_jobs.py --ignore=tests/test_update_profiles.py" + # Double the prior three-worker budget; keep native-process checks separate. + pytest_args: "-n 6 --dist loadfile --ignore=tests/cli/test_commands.py --ignore=tests/cli/test_cli_input.py --ignore=tests/cli/test_desktop_target.py --ignore=tests/cli/test_desktop_target_entrypoints.py --ignore=tests/tools/test_exec_platform.py --ignore=tests/cli/test_wsl_browser.py --ignore=tests/test_install_scripts.py --ignore=tests/test_update_jobs.py --ignore=tests/test_update_profiles.py" steps: - uses: actions/checkout@v4 @@ -139,6 +139,7 @@ jobs: # Each update job owns its venv, HOME, profile and lock directory. Preserve # the real installation/restore checks, but avoid a loadfile straggler and # disk contention with timing-sensitive runtime-registration checks. + # Keep three update workers; the six-worker trial exceeded supervisor deadlines. - name: Run Windows isolated update jobs if: runner.os == 'Windows' && github.event_name != 'push' && needs.changes.outputs.native_required == 'true' run: >- @@ -266,8 +267,8 @@ jobs: uv tool install pipx==1.17.12 uv tool dir --bin >> "$GITHUB_PATH" - # Each case owns an isolated manager/config root. Keep the existing - # four-worker budget, independent of process-identity compatibility checks. + # Each case owns an isolated manager/config root. Keep four workers: + # eight-way installer startup exceeded the existing command deadlines in CI. - name: Run Windows installer checks run: >- uv run --no-sync python -m pytest tests/test_install_scripts.py diff --git a/.github/workflows/native-acceptance.yml b/.github/workflows/native-acceptance.yml index d377d7b7d..4ae00231c 100644 --- a/.github/workflows/native-acceptance.yml +++ b/.github/workflows/native-acceptance.yml @@ -117,7 +117,7 @@ jobs: run: | python -I scripts/verify_packaged_update.py \ --wheel "$ACCEPTANCE_WHEEL" --commit "$ACCEPTANCE_COMMIT" \ - --output "$RUNNER_TEMP/packaged-update" + --output "$RUNNER_TEMP/packaged-update" --workers 2 # Raw acceptance logs contain disposable credentials. Export only structured evidence. - name: Retain native acceptance evidence @@ -131,5 +131,6 @@ jobs: ${{ runner.temp }}/packaged-update/packaged-update-report.json ${{ runner.temp }}/packaged-update/packaged-update-timings.json ${{ runner.temp }}/packaged-update/*/result.json + ${{ runner.temp }}/packaged-update/lane-*/run/*/result.json if-no-files-found: error retention-days: 3 diff --git a/conftest.py b/conftest.py index 234a74470..9a139df42 100644 --- a/conftest.py +++ b/conftest.py @@ -5,7 +5,7 @@ from __future__ import annotations import os import ssl import sys -from collections.abc import Iterator +from collections.abc import Callable, Iterator from pathlib import Path from threading import Thread from uuid import uuid4 @@ -115,6 +115,58 @@ def _use_windows_system_ca_for_default_http_clients() -> Iterator[None]: ssl.create_default_context = original +@pytest.fixture(scope="session") +def create_integration_env(tmp_path_factory: pytest.TempPathFactory) -> Callable[[Path], Path]: + """Seed each stdlib-created prefix from private, offline pip images.""" + import ensurepip + import venv + from importlib.resources import files + + from virtualenv import session_via_cli + + seed = tmp_path_factory.mktemp("integration-env-seed") + wheels = seed / "wheels" + wheels.mkdir() + versions = {} + # Keep the stdlib seed versions, including setuptools on Python 3.11, + # rather than silently selecting virtualenv's newer bundled pip. + for wheel in files("ensurepip").joinpath("_bundled").iterdir(): + if wheel.name.endswith(".whl"): + name, version, _ = wheel.name.split("-", 2) + versions[name] = version + (wheels / wheel.name).write_bytes(wheel.read_bytes()) + assert versions["pip"] == ensurepip.version() + + env = {key: value for key, value in os.environ.items() if not key.startswith(("VIRTUALENV_", "PIP_"))} + env.update({ + "VIRTUALENV_CONFIG_FILE": os.devnull, + "VIRTUALENV_OVERRIDE_APP_DATA": str(seed / "app-data"), + "PIP_CONFIG_FILE": os.devnull, + "PIP_NO_INDEX": "1", + }) + options = [ + "--python", sys.executable, + "--creator", "venv", + "--seeder", "app-data", + "--copies", + "--no-download", + "--no-periodic-update", + "--pip", versions["pip"], + "--setuptools", versions.get("setuptools", "none"), + "--extra-search-dir", str(wheels), + ] + + def create(environment: Path) -> Path: + # Keep stdlib creation semantics; use virtualenv only for copied seed + # packages and prefix-specific launchers, not its runtime import hooks. + venv.EnvBuilder(with_pip=False).create(environment) + with session_via_cli([str(environment), *options], setup_logging=False, env=env) as session: + session.seeder.run(session.creator) + return environment / ("Scripts/python.exe" if os.name == "nt" else "bin/python") + + return create + + @pytest.fixture def create_symlink(): """Create real symlinks, skipping only Windows' missing-privilege error.""" diff --git a/nanobot/channels/linear/tests/test_linear.py b/nanobot/channels/linear/tests/test_linear.py index 7b3160f63..4656d0400 100644 --- a/nanobot/channels/linear/tests/test_linear.py +++ b/nanobot/channels/linear/tests/test_linear.py @@ -580,8 +580,13 @@ async def test_graphql_non_json_server_error_is_retryable(tmp_path: Path) -> Non @pytest.mark.asyncio -async def test_graphql_rate_limit_error_is_retryable(tmp_path: Path) -> None: - reset_at = int((time.time() + 60) * 1000) +async def test_graphql_rate_limit_error_is_retryable( + tmp_path: Path, + monkeypatch: pytest.MonkeyPatch, +) -> None: + now = 1_800_000_000.0 + reset_at = int((now + 60) * 1000) + monkeypatch.setattr(linear_client, "time", SimpleNamespace(time=lambda: now + 12.5)) def handler(_request: httpx.Request) -> httpx.Response: return httpx.Response( @@ -596,7 +601,7 @@ async def test_graphql_rate_limit_error_is_retryable(tmp_path: Path) -> None: ) state = LinearStateStore(tmp_path / "linear.sqlite3") - state.save_installation(_installation()) + state.save_installation(replace(_installation(), expires_at=now + 3600)) http = httpx.AsyncClient(transport=httpx.MockTransport(handler)) client = LinearClient(_config(), state, http) try: @@ -607,7 +612,7 @@ async def test_graphql_rate_limit_error_is_retryable(tmp_path: Path) -> None: assert error.value.retryable is True assert error.value.retry_after is not None - assert 50 <= error.value.retry_after <= 60 + assert error.value.retry_after == 47.5 @pytest.mark.asyncio diff --git a/pyproject.toml b/pyproject.toml index 9ea93b9b8..4910e4866 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -103,6 +103,7 @@ dev = [ "aiohttp>=3.9.0,<4.0.0", "pytest-cov>=6.0.0,<7.0.0", "pytest-xdist>=3.8.0,<4.0.0", + "virtualenv>=20.35.4,<21.0.0", "ruff>=0.1.0", "basedpyright>=1.39.0,<2.0.0", "setproctitle>=1.3.7,<2.0.0", diff --git a/scripts/install.ps1 b/scripts/install.ps1 index ecf2bc6b4..6cc9fadd0 100644 --- a/scripts/install.ps1 +++ b/scripts/install.ps1 @@ -55,6 +55,17 @@ function Show-Usage { Write-Host "For current main, clone the repository and run 'python -m pip install -e .'." } +function Test-AvailableCommand { + param([string]$Name) + # Get-Command can import modules for missing tools, even with an application filter. + # Enumerate session/PATH commands instead, retaining existing functions and aliases. + foreach ($Command in $ExecutionContext.InvokeCommand.GetCommands( + $Name, [System.Management.Automation.CommandTypes]::All, $false)) { + return $true + } + return $false +} + function Test-Python { param([string]$Command) try { @@ -67,7 +78,7 @@ function Test-Python { function Find-Python { if ($env:PYTHON) { - if (Get-Command $env:PYTHON -ErrorAction SilentlyContinue) { + if (Test-AvailableCommand $env:PYTHON) { if (Test-Python $env:PYTHON) { return $env:PYTHON } @@ -77,7 +88,7 @@ function Find-Python { } foreach ($Candidate in @("python", "py")) { - if (Get-Command $Candidate -ErrorAction SilentlyContinue) { + if (Test-AvailableCommand $Candidate) { if (Test-Python $Candidate) { return $Candidate } @@ -108,12 +119,12 @@ function Get-InstallMethod { } $Existing = @() - if (Get-Command uv -ErrorAction SilentlyContinue) { + if (Test-AvailableCommand uv) { $ToolDir = & uv tool dir if ($LASTEXITCODE -ne 0 -or -not $ToolDir) { Fail "Could not inspect the uv tools directory." } if (Test-Path -LiteralPath (Join-Path $ToolDir $Package)) { $Existing += "uv" } } - if (Get-Command pipx -ErrorAction SilentlyContinue) { + if (Test-AvailableCommand pipx) { $ToolDir = & pipx environment --value PIPX_LOCAL_VENVS if ($LASTEXITCODE -ne 0 -or -not $ToolDir) { Fail "Could not inspect the pipx environments directory." } if (Test-Path -LiteralPath (Join-Path $ToolDir $Package)) { $Existing += "pipx" } diff --git a/scripts/verify_packaged_update.py b/scripts/verify_packaged_update.py index 06035e33a..c98e89194 100644 --- a/scripts/verify_packaged_update.py +++ b/scripts/verify_packaged_update.py @@ -21,19 +21,29 @@ import os import platform import re import secrets +import signal import socket import sqlite3 import subprocess import sys import time -from contextlib import closing, contextmanager +from contextlib import ExitStack, closing, contextmanager from pathlib import Path +from typing import TYPE_CHECKING from unittest.mock import patch from urllib.parse import quote from zipfile import ZIP_DEFLATED, ZipFile +if TYPE_CHECKING: + from nanobot.agent.tools._windows_job import WindowsJob + SCENARIOS = ("upgrade", "upgrade-again", "skipped-preview", "import-failure", "restart-failure", "backup-failure", "worker-exit", "metadata-loss", "restore-interruption") +TWO_JOURNEY_SCENARIOS = {"upgrade-again", "import-failure", "restart-failure", "backup-failure", + "metadata-loss", "restore-interruption"} +# Each lane retains the existing per-command deadlines and cleanup. This outer +# bound also covers a stuck controller; it is not permission to leave it running. +LANE_TIMEOUT = 30 * 60 def digest(path: Path) -> str: @@ -68,15 +78,23 @@ class Timings: "seconds": time.perf_counter() - started, "status": "succeeded" if succeeded else "failed"} self.records.append(record) - # The controller owns this exclusive root before starting any timer. - # Replace the checkpoint atomically so a later failed phase cannot - # leave a partially written report. This is not a durability/fsync test. - temporary = self.output.with_suffix(".tmp") - write(temporary, {"schema_version": 1, "clock": "perf_counter", "timings": self.records}) - temporary.replace(self.output) + self.checkpoint() label = "/".join(str(value) for value in (scenario, journey, phase) if value is not None) print(f"TIMING {label}: {record['seconds']:.3f}s ({record['status']})", flush=True) + def checkpoint(self) -> None: + # Each controller owns its file. The parent imports only settled lane + # checkpoints, never raw logs or concurrent writes to a shared report. + temporary = self.output.with_suffix(".tmp") + write(temporary, {"schema_version": 1, "clock": "perf_counter", "timings": self.records}) + temporary.replace(self.output) + + def merge(self, source: Path, worker: int) -> None: + keys = ("phase", "scenario", "journey", "seconds", "status") + self.records.extend({**{key: row[key] for key in keys}, "worker": worker} + for row in read(source)["timings"]) + self.checkpoint() + def replace_once(source: bytes, old: bytes, new: bytes) -> bytes: if source.count(old) != 1: @@ -620,28 +638,170 @@ def verify_data(root: Path, expected: str) -> bool: return sqlite_expected -def run(args) -> dict: +def isolated_environment(root: Path) -> dict[str, str]: + from scripts.verify_installed_release import host_environment + + system = host_environment(dict(os.environ)) + system.update(HOME=str(root), USERPROFILE=str(root), APPDATA=str(root / "config"), + LOCALAPPDATA=str(root / "data"), XDG_CONFIG_HOME=str(root / "config"), + XDG_CACHE_HOME=str(root / "cache"), XDG_DATA_HOME=str(root / "data"), + TMPDIR=str(root), TMP=str(root), TEMP=str(root), + PIP_CONFIG_FILE=os.devnull, PIP_NO_INPUT="1", PIP_DISABLE_PIP_VERSION_CHECK="1", PYTHONUTF8="1", + NANOBOT_TUI_NO_DOWNLOAD="1", NO_COLOR="1", PATH=os.defpath) + if os.name == "nt": + system["PATH"] = str(Path(system["SYSTEMROOT"]) / "System32") + return system + + +def scenario_groups(scenarios: list[str], workers: int) -> list[list[str]]: + groups: list[list[str]] = [[] for _ in range(min(workers, len(scenarios)))] + loads = [0] * len(groups) + for scenario in scenarios: + lane = min(range(len(groups)), key=loads.__getitem__) + groups[lane].append(scenario) + loads[lane] += 1 + (scenario in TWO_JOURNEY_SCENARIOS) + return groups + + +def check_coverage(results: list[dict], scenarios: list[str]) -> None: + if [result["scenario"] for result in results] != scenarios: + raise ValueError("Lane report does not cover its assigned scenarios in order") + for result in results: + if ("subsequent_update" in result) != (result["scenario"] in TWO_JOURNEY_SCENARIOS): + raise ValueError("Lane report does not cover every required upgrade journey") + + +def stop_controller(process: subprocess.Popen, owner: WindowsJob | None) -> None: + # Tree ownership outlives the controller: an exited supervisor can leave an + # installer running. Clear that tree before stopping its detached gateways. + if owner is not None: + owner.terminate() + else: + try: + os.killpg(process.pid, signal.SIGKILL) + except ProcessLookupError: + pass + process.wait(timeout=15) + + +def cleanup_lane(output: Path, scenarios: list[str]) -> None: + """After abnormal controller exit, stop only its explicitly configured gateways.""" + from scripts.verify_installed_release import _wait_for_closed_listeners + + # Use the controller's installed package, not the potentially interrupted + # managed venv. Gateway stop validates the recorded process identity itself. + failed = False + with (output.parent / "cleanup.log").open("w", encoding="utf-8") as log: + for scenario in scenarios: + case_root = output / scenario + config_file = case_root / "account/.nanobot/config.json" + if not config_file.exists(): + continue + try: + env = isolated_environment(case_root / "account") + env.update(TMPDIR=str(case_root), TMP=str(case_root), TEMP=str(case_root)) + subprocess.run([sys.executable, "-I", "-B", "-m", "nanobot", "gateway", "stop", "--config", + str(config_file)], env=env, cwd=case_root, stdout=log, stderr=log, + timeout=60, check=True) + config = read(config_file) + _wait_for_closed_listeners((config["gateway"]["port"], config["channels"]["websocket"]["port"])) + except Exception: + failed = True + if failed: + raise RuntimeError("A lane gateway did not finish bounded cleanup") + + +def run_parallel(args, root: Path, target: Path, version: str, original_hash: str, + scenarios: list[str], timings: Timings) -> list[dict]: + groups = scenario_groups(scenarios, args.workers) + jobs = [] + failed = False + with timings.measure("parallel_total"), ExitStack() as stack: + try: + deadline = time.monotonic() + LANE_TIMEOUT + for worker, selected in enumerate(groups, 1): + lane = root / f"lane-{worker}" + lane.mkdir(mode=0o700) + output = lane / "run" # The child exclusively creates this root. + env = isolated_environment(lane) + # Controller dependencies are shared read-only; do not write + # bytecode into their environment from either lane. + command = [sys.executable, "-I", "-B", str(Path(__file__).resolve()), "--wheel", str(target), + "--commit", args.commit, "--output", str(output), "--workers", "1"] + if args.baseline_wheel: + command.extend(("--baseline-wheel", str(args.baseline_wheel.resolve(strict=True)))) + if args.dock: + command.append("--dock") + for scenario in selected: + command.extend(("--scenario", scenario)) + # No child stdout/stderr is replayed. It can contain credentials, + # including assertion messages and dynamically issued API tokens. + log = stack.enter_context((lane / "controller.log").open("w", encoding="utf-8")) + owner = None + flags = 0 + if os.name == "nt": + from nanobot.agent.tools._windows_job import WindowsJob + + owner = stack.enter_context(closing(WindowsJob.create())) + flags = subprocess.CREATE_NEW_PROCESS_GROUP | owner.creation_flags + process = subprocess.Popen(command, env=env, cwd=lane, stdout=log, stderr=log, + start_new_session=os.name != "nt", creationflags=flags) + if owner is not None: + try: + owner.assign_and_resume(process.pid) + except BaseException: + if process.poll() is None: + process.kill() + process.wait(timeout=15) + raise + jobs.append((worker, selected, output, process, owner)) + for worker, _, _, process, _ in jobs: + try: + status = process.wait(timeout=max(0, deadline - time.monotonic())) + except subprocess.TimeoutExpired: + failed = True + print(f"FAIL lane-{worker}: controller deadline exceeded", flush=True) + break + if status: + failed = True + print(f"FAIL lane-{worker}: controller exited with status {status}", flush=True) + finally: + cleanup_failed = False + # Finish or terminate every owned controller before importing JSON. + # An ordinary failing lane does not interrupt another lane's cleanup. + for _, selected, output, process, owner in jobs: + try: + stop_controller(process, owner) + if process.returncode: + cleanup_lane(output, selected) + except Exception: + cleanup_failed = True + for worker, _, output, _, _ in jobs: + checkpoint = output / "packaged-update-timings.json" + if checkpoint.exists(): + timings.merge(checkpoint, worker) + if cleanup_failed: + raise RuntimeError("A lane did not finish bounded cleanup") + if failed: + raise RuntimeError("Packaged update lane failed; raw logs remain private") + results = {} + for _, selected, output, _, _ in jobs: + report = read(output / "packaged-update-report.json") + if (report["target_sha256"] != original_hash or report["candidate_commit"] != args.commit + or report["version"] != version): + raise ValueError("Lane did not verify the original candidate wheel") + check_coverage(report["scenarios"], selected) + results.update((result["scenario"], result) for result in report["scenarios"]) + return [results[scenario] for scenario in scenarios] + + +def run_serial(args, root: Path, target: Path, version: str, original_hash: str, + scenarios: list[str], timings: Timings) -> list[dict]: from packaging.utils import parse_wheel_filename from packaging.version import Version - # The build environment supplies dependencies for metadata construction only. - # All product imports and execution happen in the separately installed wheel. - sys.path.insert(0, str(Path(__file__).resolve().parents[1])) - from scripts.build_tui_wheels import wheel_files - from scripts.verify_installed_release import _wait_for_closed_listeners, host_environment + from scripts.verify_installed_release import _wait_for_closed_listeners - target = args.wheel.resolve(strict=True) - version = str(parse_wheel_filename(target.name)[1]) - tags = parse_wheel_filename(target.name)[3] - if len(tags) != 1 or any(tag.platform == "any" for tag in tags): - raise ValueError("Acceptance requires the final native wheel, not an intermediate universal wheel") - files, _, _ = wheel_files(target, version, platform=next(iter(tags)).platform) - if files["nanobot/_build_commit.txt"].decode().strip() != args.commit: - raise ValueError("Target wheel does not contain the requested candidate commit") - original_hash = digest(target) - root = args.output.resolve() - root.mkdir(mode=0o700) # Exclusive evidence root. Never use a user's installation. - timings = Timings(root / "packaged-update-timings.json") environment = root / "managed" python = environment / ("Scripts/python.exe" if os.name == "nt" else "bin/python") base = Version(version).release @@ -654,25 +814,17 @@ def run(args) -> dict: if Version(baseline_version) >= Version(version): raise ValueError("Baseline must precede the target") results = [] - system = host_environment(dict(os.environ)) - system.update(HOME=str(root), USERPROFILE=str(root), APPDATA=str(root / "config"), - LOCALAPPDATA=str(root / "data"), XDG_CONFIG_HOME=str(root / "config"), - XDG_CACHE_HOME=str(root / "cache"), XDG_DATA_HOME=str(root / "data"), - TMPDIR=str(root), TMP=str(root), TEMP=str(root), - PIP_CONFIG_FILE=os.devnull, PIP_NO_INPUT="1", PIP_DISABLE_PIP_VERSION_CHECK="1", PYTHONUTF8="1", - NANOBOT_TUI_NO_DOWNLOAD="1", NO_COLOR="1", PATH=os.defpath) - if os.name == "nt": - system["PATH"] = str(Path(system["SYSTEMROOT"]) / "System32") - # Install once, without inherited user pip settings; every case resets only - # nanobot in this private environment. Dependencies stay pinned by its snapshot. + system = isolated_environment(root) + # Install once per lane, without inherited user pip settings; every case + # resets only nanobot. No mutable venv or dependency snapshot crosses lanes. with timings.measure("venv"): - subprocess.run([sys.executable, "-I", "-m", "venv", str(environment)], check=True, env=system, timeout=90) + subprocess.run([sys.executable, "-I", "-B", "-m", "venv", str(environment)], check=True, env=system, timeout=90) with timings.measure("initial_dependency_install"): subprocess.run([str(python), "-I", "-m", "pip", "install", "--only-binary=:all:", str(target)], check=True, env=system, timeout=600, stdout=subprocess.DEVNULL) write(environment / "nanobot-install.json", {"schema_version": 1, "owner": "nanobot-installer", "environment": str(environment), "extras": []}) - for scenario in args.scenario or SCENARIOS: + for scenario in scenarios: with timings.measure("scenario_total", scenario=scenario): with timings.measure("fixture", scenario=scenario, journey=1): case_root = root / scenario @@ -747,15 +899,6 @@ def run(args) -> dict: assert result["subsequent_update"]["phase"] == "succeeded" write(case_root / "result.json", result) results.append(result) - except (subprocess.CalledProcessError, subprocess.TimeoutExpired): - log.flush() - tail = (case_root / "acceptance.log").read_text(encoding="utf-8", errors="replace")[-8192:] - config_file = account / ".nanobot/config.json" - if config_file.exists(): - token = read(config_file)["channels"]["websocket"]["tokenIssueSecret"] - tail = tail.replace(token, "[redacted]") - print(tail, file=sys.stderr) - raise finally: with timings.measure("cleanup", scenario=scenario): subprocess.run([str(python), "-I", "-m", "nanobot", "gateway", "stop", "--config", @@ -776,11 +919,42 @@ def run(args) -> dict: _wait_dock(Path(dock_address), present=False) results[-1]["dock_stopped"] = True print(f"PASS {scenario}: {results[-1]['phase']}", flush=True) + return results + + +def run(args) -> dict: + from packaging.utils import parse_wheel_filename + + # The build environment supplies dependencies for metadata construction only. + # Product phases run in the separately installed wheel, never this checkout. + sys.path.insert(0, str(Path(__file__).resolve().parents[1])) + from scripts.build_tui_wheels import wheel_files + + target = args.wheel.resolve(strict=True) + _, parsed_version, _, tags = parse_wheel_filename(target.name) + version = str(parsed_version) + if len(tags) != 1 or any(tag.platform == "any" for tag in tags): + raise ValueError("Acceptance requires the final native wheel, not an intermediate universal wheel") + files, _, _ = wheel_files(target, version, platform=next(iter(tags)).platform) + if files["nanobot/_build_commit.txt"].decode().strip() != args.commit: + raise ValueError("Target wheel does not contain the requested candidate commit") + original_hash = digest(target) + scenarios = list(args.scenario or SCENARIOS) + if len(set(scenarios)) != len(scenarios): + raise ValueError("Select each scenario only once") + root = args.output.resolve() + root.mkdir(mode=0o700) # Exclusive evidence root. Never use a user's installation. + timings = Timings(root / "packaged-update-timings.json") + workers = min(args.workers, len(scenarios)) + runner = run_parallel if workers > 1 else run_serial + results = runner(args, root, target, version, original_hash, scenarios, timings) + check_coverage(results, scenarios) assert digest(target) == original_hash return {"platform": platform.system(), "machine": platform.machine(), "python": platform.python_version(), "target_sha256": original_hash, "candidate_commit": args.commit, "version": version, "release_transport": "local fixture; no public-download proof", "interactive_ui_e2e": False, - "release_approval": "private unsigned fixture; not signature acceptance", + "release_approval": "private unsigned fixture; not signature acceptance", "workers": workers, + "scenario_count": len(results), "journey_count": sum(1 + ("subsequent_update" in result) for result in results), "scenarios": results} @@ -791,9 +965,13 @@ def main() -> None: parser.add_argument("--commit") parser.add_argument("--output", required=True, type=Path) parser.add_argument("--scenario", action="append", choices=SCENARIOS) + parser.add_argument("--workers", type=int, default=1, + help="Maximum independent lanes, each with its own installation (default: 1)") parser.add_argument("--dock", action="store_true", help="Verify native macOS background Dock lifecycle") parser.add_argument("--phase", choices=("prepare", "verify"), help=argparse.SUPPRESS) args = parser.parse_args() + if args.workers < 1: + parser.error("--workers must be positive") if not sys.flags.isolated: parser.error("Run with python -I") if args.dock and sys.platform != "darwin": @@ -808,8 +986,13 @@ def main() -> None: return if not args.wheel or not args.commit: parser.error("--wheel and --commit are required") - result = run(args) - write(args.output / "packaged-update-report.json", result) + try: + result = run(args) + write(args.output / "packaged-update-report.json", result) + except Exception as error: + # Exception values/commands can include temporary credentials. Only the + # structured checkpoints and this safe class name may leave the account. + raise SystemExit(f"Packaged update verification failed ({type(error).__name__}); raw logs remain private") from None if __name__ == "__main__": diff --git a/tests/test_install_scripts.py b/tests/test_install_scripts.py index 0bb626bb9..4598c1750 100644 --- a/tests/test_install_scripts.py +++ b/tests/test_install_scripts.py @@ -204,6 +204,54 @@ def test_installer_starts_and_upgrades_same_persistent_manager_environment(sandb assert not (sandbox["root"] / "managed").exists() +@pytest.mark.skipif(not WINDOWS, reason="Windows PowerShell command discovery") +def test_powershell_manager_discovery_keeps_session_functions_without_importing_modules(sandbox): + shell = shutil.which("powershell") + if not shell: + pytest.skip("Windows PowerShell is required") + uv = Path(_expose(sandbox, "uv")) + _wheel(sandbox["wheels"], "0.0.1") + _run([str(uv), "tool", "install", "--python", BASE_PYTHON, "nanobot-ai"], sandbox) + prefix = sandbox["root"] / "uv-tools/nanobot-ai" + # The session function is the only uv command; its real executable is not on PATH. + native = sandbox["root"] / "native" + native.mkdir() + uv = uv.rename(native / "uv.exe") + _wheel(sandbox["wheels"], "0.0.2") + + def ps_literal(value): + return "'" + str(value).replace("'", "''") + "'" + + modules = sandbox["root"] / "modules" + decoy = modules / "InstallerDecoy" + decoy.mkdir(parents=True) + marker = sandbox["root"] / "module-imported" + (decoy / "InstallerDecoy.psd1").write_text( + "@{ RootModule = 'InstallerDecoy.psm1'; ModuleVersion = '1.0'; FunctionsToExport = @('pipx') }\n", + encoding="utf-8-sig", + ) + (decoy / "InstallerDecoy.psm1").write_text( + f"[IO.File]::WriteAllText({ps_literal(marker)}, 'imported')\n" + "function pipx { throw 'Manager discovery imported an unrelated module' }\n", + encoding="utf-8-sig", + ) + sandbox["env"]["PSModuleAnalysisCachePath"] = str(sandbox["root"] / "module-analysis-cache") + command = ( + f"$env:PSModulePath = {ps_literal(modules)} + ';' + $PSHOME + '\\Modules'\n" + f"function uv {{ & {ps_literal(uv)} @args }}\n" + f"& {ps_literal(SCRIPTS / 'install.ps1')}" + ) + result = _run([shell, "-NoProfile", "-NonInteractive", "-ExecutionPolicy", "Bypass", + "-Command", command], sandbox, check=False) + assert not marker.exists(), result.stdout + result.stderr + assert result.returncode == 0, result.stdout + result.stderr + identity = _identity(result) + assert identity["version"] == "0.0.2" + assert Path(identity["prefix"]).resolve() == prefix + assert identity["isolated"] == 1 + assert not (sandbox["root"] / "managed").exists() + + def test_rerunning_installer_preserves_uv_version_constraint(sandbox): uv = _expose(sandbox, "uv") _wheel(sandbox["wheels"], "0.0.1") diff --git a/tests/test_integration_env.py b/tests/test_integration_env.py new file mode 100644 index 000000000..92123fb3f --- /dev/null +++ b/tests/test_integration_env.py @@ -0,0 +1,119 @@ +"""Real offline seed/install checks for disposable integration environments.""" + +import ensurepip +import json +import os +import subprocess +from importlib.resources import files +from io import BytesIO +from pathlib import Path +from zipfile import ZipFile + +_PROBE = """ +import importlib.metadata as metadata +import json +import os +import sys +from pathlib import Path +import pip + +distribution = metadata.distribution('pip') +script = 'pip.exe' if os.name == 'nt' else 'pip' +print(json.dumps({ + 'prefix': sys.prefix, + 'python': sys.executable, + 'pip': pip.__file__, + 'pip_version': pip.__version__, + 'creation_command': dict(line.split(' = ', 1) for line in + (Path(sys.prefix) / 'pyvenv.cfg').read_text(encoding='utf-8').splitlines())['command'], + 'versions': {dist.metadata['Name']: dist.version for dist in metadata.distributions()}, + 'pip_scripts': [str(distribution.locate_file(path)) for path in distribution.files + if Path(distribution.locate_file(path)).name == script], +})) +""" + + +def _run(*command): + return subprocess.run(command, check=True, capture_output=True, text=True, timeout=30).stdout + + +def _assert_stdlib_seed(state): + bundled = files("ensurepip").joinpath("_bundled") + versions = {wheel.name.split("-")[0]: wheel.name.split("-")[1] + for wheel in bundled.iterdir() if wheel.name.endswith(".whl")} + assert state["versions"] == versions + pip = bundled.joinpath(f"pip-{ensurepip.version()}-py3-none-any.whl") + site = Path(state["pip"]).parent.parent + with ZipFile(BytesIO(pip.read_bytes())) as archive: + for member in archive.infolist(): + if member.filename.startswith("pip/") and not member.is_dir(): + assert (site / member.filename).read_bytes() == archive.read(member) + + +def _wheel(directory: Path, version: str) -> Path: + dist = f"seed_probe-{version}.dist-info" + files = { + "seed_probe/__init__.py": ( + "def main():\n" + " import importlib.metadata as metadata, json, sys\n" + " print(json.dumps([sys.prefix, sys.executable, metadata.version('seed-probe')]))\n" + ), + f"{dist}/METADATA": f"Metadata-Version: 2.1\nName: seed-probe\nVersion: {version}\n", + f"{dist}/WHEEL": "Wheel-Version: 1.0\nRoot-Is-Purelib: true\nTag: py3-none-any\n", + f"{dist}/entry_points.txt": "[console_scripts]\nseed-probe = seed_probe:main\n", + } + record = f"{dist}/RECORD" + files[record] = "".join(f"{name},,\n" for name in [*files, record]) + path = directory / f"seed_probe-{version}-py3-none-any.whl" + with ZipFile(path, "w") as archive: + for name, content in files.items(): + archive.writestr(name, content) + return path + + +def test_seeded_pip_and_installed_scripts_use_independent_prefixes(create_integration_env, tmp_path, monkeypatch): + for name in tuple(os.environ): + if name.startswith("PIP_"): + monkeypatch.delenv(name) + monkeypatch.setenv("PIP_CONFIG_FILE", os.devnull) + monkeypatch.setenv("PIP_NO_INDEX", "1") + monkeypatch.setenv("PIP_DISABLE_PIP_VERSION_CHECK", "1") + monkeypatch.setenv("PIP_NO_CACHE_DIR", "1") + monkeypatch.delenv("PYTHONPATH", raising=False) + + first = create_integration_env(tmp_path / "first prefix with spaces") + first_state = json.loads(_run(str(first), "-I", "-c", _PROBE)) + _assert_stdlib_seed(first_state) + _run(str(first), "-I", "-m", "pip", "install", "--no-deps", str(_wheel(tmp_path, "1.0.0"))) + + # Update integration cases deliberately rewrite this entrypoint. The next + # prefix must still be seeded from an unchanged image, not that live pip. + entrypoint = Path(first_state["pip"]).with_name("__main__.py") + entrypoint.write_text("raise SystemExit('test-owned pip mutation')\n", encoding="utf-8") + changed = subprocess.run([str(first), "-I", "-m", "pip", "--version"], + capture_output=True, text=True, timeout=30) + assert changed.returncode != 0 and "test-owned pip mutation" in changed.stderr + + second = create_integration_env(tmp_path / "second prefix with spaces") + second_state = json.loads(_run(str(second), "-I", "-c", _PROBE)) + _assert_stdlib_seed(second_state) + assert "seed-probe" not in second_state["versions"] + assert _run(str(second), "-I", "-m", "pip", "--version").startswith(f"pip {ensurepip.version()} ") + for python, state in ((first, first_state), (second, second_state)): + assert Path(state["prefix"]).resolve() == python.parent.parent.resolve() + assert Path(state["python"]).resolve() == python.resolve() + assert Path(state["pip"]).resolve().is_relative_to(python.parent.parent.resolve()) + assert state["pip_version"] == state["versions"]["pip"] == ensurepip.version() + assert " -m venv " in state["creation_command"] + pip = python.parent / ("pip.exe" if os.name == "nt" else "pip") + assert [Path(path).resolve() for path in state["pip_scripts"]] == [pip.resolve()] + assert _run(str(pip), "--version").startswith(f"pip {ensurepip.version()} from {Path(state['pip']).parent}") + assert f"sys.executable: {python}" in _run(str(pip), "debug") + + _run(str(second), "-I", "-m", "pip", "install", "--no-deps", str(_wheel(tmp_path, "2.0.0"))) + for python, version in ((first, "1.0.0"), (second, "2.0.0")): + command = python.parent / ("seed-probe.exe" if os.name == "nt" else "seed-probe") + prefix, executable, installed = json.loads(_run(str(command))) + assert Path(prefix).resolve() == python.parent.parent.resolve() + assert Path(executable).resolve() == python.resolve() + assert installed == version diff --git a/tests/test_packaged_update_probe.py b/tests/test_packaged_update_probe.py index 5debcf1c2..1c20b88aa 100644 --- a/tests/test_packaged_update_probe.py +++ b/tests/test_packaged_update_probe.py @@ -5,8 +5,11 @@ import csv import hashlib import io import json +import socket import subprocess import sys +import textwrap +from argparse import Namespace from pathlib import Path from zipfile import ZipFile, ZipInfo @@ -14,6 +17,7 @@ import httpx import pytest from nanobot.release_feed import ReleaseFeed +from scripts import verify_packaged_update as probe from scripts.verify_packaged_update import ( Timings, assert_canonical_preserved, @@ -253,3 +257,332 @@ def test_timings_persist_failure_and_finally_cleanup_without_exporting_secrets(t assert secret not in captured.out + captured.err assert "TIMING restart-failure/2/worker:" in captured.out assert "TIMING restart-failure/scenario_total:" in captured.out + + +def test_worker_count_must_be_positive_before_creating_output(tmp_path): + script = Path(probe.__file__).resolve() + output = tmp_path / "must-not-exist" + result = subprocess.run([sys.executable, "-I", str(script), "--output", str(output), "--workers", "0"], + capture_output=True, text=True, timeout=10) + assert result.returncode == 2 and "--workers" in result.stderr + assert not output.exists() + + +def test_lanes_balance_all_nine_scenarios_without_splitting_fifteen_journeys(): + scenarios = list(probe.SCENARIOS) + assert probe.scenario_groups(scenarios, 1) == [scenarios] + groups = probe.scenario_groups(scenarios, 2) + assert groups == [ + ["upgrade", "skipped-preview", "import-failure", "backup-failure", "restore-interruption"], + ["upgrade-again", "restart-failure", "worker-exit", "metadata-loss"], + ] + assert sorted(scenario for group in groups for scenario in group) == sorted(scenarios) + assert [sum(1 + (scenario in probe.TWO_JOURNEY_SCENARIOS) for scenario in group) for group in groups] == [8, 7] + assert probe.scenario_groups(["metadata-loss"], 2) == [["metadata-loss"]] + for workers in (3, 4): + groups = probe.scenario_groups(scenarios, workers) + assert len(groups) == workers + assert sorted(scenario for group in groups for scenario in group) == sorted(scenarios) + assert sum(1 + (scenario in probe.TWO_JOURNEY_SCENARIOS) + for group in groups for scenario in group) == 15 + + +def parallel_controller(tmp_path, monkeypatch, *, mode="success"): + """Real stdlib-only controllers exercise orchestration, not native acceptance.""" + script = tmp_path / "fake_controller.py" + script.write_text(f"MODE = {mode!r}\nTWO = {sorted(probe.TWO_JOURNEY_SCENARIOS)!r}\n" + textwrap.dedent('''\ + import argparse + import hashlib + import json + import os + import subprocess + import sys + import time + from pathlib import Path + + parser = argparse.ArgumentParser() + parser.add_argument("--wheel", type=Path) + parser.add_argument("--commit") + parser.add_argument("--output", type=Path) + parser.add_argument("--workers", type=int) + parser.add_argument("--scenario", action="append") + parser.add_argument("--baseline-wheel") + parser.add_argument("--dock", action="store_true") + args = parser.parse_args() + output, lane = args.output, args.output.parent + output.mkdir() + worker = int(lane.name[-1]) + def write(path, value): + path.write_text(json.dumps(value), encoding="utf-8") + keys = ("HOME", "USERPROFILE", "APPDATA", "LOCALAPPDATA", "XDG_CONFIG_HOME", + "XDG_DATA_HOME", "XDG_CACHE_HOME", "TMPDIR", "TMP", "TEMP", "PIP_INDEX_URL") + write(lane / "environment.json", {"env": {key: os.environ.get(key) for key in keys}, + "workers": args.workers, "baseline_wheel": args.baseline_wheel, + "isolated": sys.flags.isolated, "no_bytecode": sys.flags.dont_write_bytecode, "pid": os.getpid()}) + (lane / "ready").touch() + # A serial parent would time out here instead of ever starting lane 2. + deadline = time.monotonic() + 8 + while not all((lane.parent / f"lane-{number}/ready").exists() for number in (1, 2)): + if time.monotonic() > deadline: + raise RuntimeError("Controllers did not overlap") + time.sleep(0.02) + secret = "temporary-api-token-must-stay-in-private-logs" + print(secret, flush=True) + print(secret, file=sys.stderr, flush=True) + write(output / "packaged-update-timings.json", {"schema_version": 1, "clock": "perf_counter", + "timings": [{"phase": "fixture", "scenario": args.scenario[0], "journey": 1, + "seconds": 0.01, "status": "failed" if MODE == "exit" and worker == 1 else "succeeded"}]}) + if MODE == "timeout" or (MODE == "exit-with-child" and worker == 1): + # The descendant owns a real listener, even if its controller exits. + child = "import json, socket, sys, time; from pathlib import Path; " \ + "s = socket.socket(); s.bind(('127.0.0.1', 0)); s.listen(); " \ + "Path(sys.argv[1]).write_text(json.dumps(s.getsockname()[1])); " \ + "deadline = time.monotonic() + 60; " \ + "exec('while time.monotonic() < deadline and not Path(sys.argv[2]).exists(): time.sleep(0.02)')" + subprocess.Popen([sys.executable, "-I", "-c", child, + str(lane / "listener.json"), str(lane / "stop-listener")]) + if MODE == "exit-with-child": + deadline = time.monotonic() + 8 + while not (lane / "listener.json").exists(): + if time.monotonic() > deadline: + raise RuntimeError("Descendant listener did not start") + time.sleep(0.02) + raise SystemExit(92) + time.sleep(60) + if MODE == "exit" and worker == 1: + raise SystemExit(91) + if worker == 1: + time.sleep(0.2) + results = [] + for scenario in args.scenario: + result = {"scenario": scenario, "phase": "succeeded"} + if scenario in TWO: + result["subsequent_update"] = {"scenario": "upgrade", "phase": "succeeded"} + if MODE == "missing-journey" and scenario == "import-failure": + del result["subsequent_update"] + case = output / scenario + case.mkdir() + write(case / "result.json", result) + results.append(result) + write(output / "packaged-update-report.json", { + "target_sha256": "0" * 64 if MODE == "wrong-hash" else hashlib.sha256(args.wheel.read_bytes()).hexdigest(), + "candidate_commit": args.commit, "version": "0.3.6", "scenarios": results}) + (lane / "finished").write_text(str(time.monotonic())) + '''), encoding="utf-8") + monkeypatch.setattr(probe, "__file__", str(script)) + target = wheel(tmp_path, "0.3.6") + baseline = wheel(tmp_path, "0.3.5") + root = tmp_path / "evidence" + root.mkdir() + args = Namespace(wheel=target, baseline_wheel=baseline, output=root, commit="a" * 40, + workers=2, dock=False, scenario=None) + return args, root, Timings(root / "packaged-update-timings.json") + + +def test_parallel_controllers_isolate_accounts_and_merge_in_scenario_order(tmp_path, monkeypatch, capsys): + args, root, timings = parallel_controller(tmp_path, monkeypatch) + monkeypatch.setenv("PIP_INDEX_URL", "https://user:private-credential@example.invalid") + original_hash = digest(args.wheel) + results = probe.run_parallel(args, root, args.wheel, "0.3.6", original_hash, list(probe.SCENARIOS), timings) + assert [result["scenario"] for result in results] == list(probe.SCENARIOS) + assert sum(1 + ("subsequent_update" in result) for result in results) == 15 + assert digest(args.wheel) == original_hash + assert float((root / "lane-2/finished").read_text()) < float((root / "lane-1/finished").read_text()) + controllers = [json.loads((root / f"lane-{number}/environment.json").read_text()) for number in (1, 2)] + assert controllers[0]["pid"] != controllers[1]["pid"] + for number, controller in enumerate(controllers, 1): + assert controller["workers"] == 1 and controller["isolated"] and controller["no_bytecode"] + assert controller["baseline_wheel"] == str(args.baseline_wheel.resolve()) + for key, value in controller["env"].items(): + if key == "PIP_INDEX_URL": + assert value is None + else: + assert Path(value).is_relative_to(root / f"lane-{number}") + checkpoint = (root / "packaged-update-timings.json").read_text() + records = json.loads(checkpoint)["timings"] + assert [record.get("worker") for record in records] == [1, 2, None] + assert records[-1]["phase"] == "parallel_total" and records[-1]["status"] == "succeeded" + assert all(record["seconds"] >= 0 for record in records) + captured = capsys.readouterr() + assert "temporary-api-token" not in checkpoint + captured.out + captured.err + assert "private-credential" not in checkpoint + captured.out + captured.err + assert "temporary-api-token" in (root / "lane-1/controller.log").read_text() + + +def test_parallel_failure_is_real_and_allows_other_lane_to_finish_cleanup(tmp_path, monkeypatch, capsys): + args, root, timings = parallel_controller(tmp_path, monkeypatch, mode="exit") + with pytest.raises(RuntimeError, match="lane failed"): + probe.run_parallel(args, root, args.wheel, "0.3.6", digest(args.wheel), list(probe.SCENARIOS), timings) + assert (root / "lane-2/finished").exists() + records = json.loads(timings.output.read_text())["timings"] + assert [(record.get("worker"), record["status"]) for record in records] == [ + (1, "failed"), (2, "succeeded"), (None, "failed")] + assert not (root / "packaged-update-report.json").exists() + captured = capsys.readouterr() + assert "status 91" in captured.out + assert "temporary-api-token" not in timings.output.read_text() + captured.out + captured.err + + +def test_parallel_deadline_kills_owned_controller_trees_and_their_listeners(tmp_path, monkeypatch, capsys): + from scripts.verify_installed_release import _wait_for_closed_listeners + + args, root, timings = parallel_controller(tmp_path, monkeypatch, mode="timeout") + monkeypatch.setattr(probe, "LANE_TIMEOUT", 5) + with pytest.raises(RuntimeError, match="lane failed"): + probe.run_parallel(args, root, args.wheel, "0.3.6", digest(args.wheel), list(probe.SCENARIOS), timings) + ports = tuple(json.loads((root / f"lane-{number}/listener.json").read_text()) for number in (1, 2)) + _wait_for_closed_listeners(ports) + assert json.loads(timings.output.read_text())["timings"][-1]["status"] == "failed" + captured = capsys.readouterr() + assert "deadline exceeded" in captured.out + assert "temporary-api-token" not in timings.output.read_text() + captured.out + captured.err + + +def test_exited_controller_cannot_leave_a_descendant_listener_running(tmp_path, monkeypatch): + from scripts.verify_installed_release import _wait_for_closed_listeners + + args, root, timings = parallel_controller(tmp_path, monkeypatch, mode="exit-with-child") + listener = root / "lane-1/listener.json" + try: + with pytest.raises(RuntimeError, match="lane failed"): + probe.run_parallel(args, root, args.wheel, "0.3.6", digest(args.wheel), list(probe.SCENARIOS), timings) + _wait_for_closed_listeners((json.loads(listener.read_text()),)) + finally: + # A red baseline must not leak the process it deliberately exposed. + (root / "lane-1/stop-listener").touch() + if listener.exists(): + _wait_for_closed_listeners((json.loads(listener.read_text()),)) + + +@pytest.mark.parametrize("mode,message", [("wrong-hash", "original candidate"), ("missing-journey", "every required")]) +def test_parallel_reports_must_prove_original_hash_and_complete_journey_coverage(tmp_path, monkeypatch, mode, message): + args, root, timings = parallel_controller(tmp_path, monkeypatch, mode=mode) + with pytest.raises(ValueError, match=message): + probe.run_parallel(args, root, args.wheel, "0.3.6", digest(args.wheel), list(probe.SCENARIOS), timings) + assert json.loads(timings.output.read_text())["timings"][-1]["status"] == "failed" + + +@pytest.mark.parametrize("stop_failure", [False, True]) +def test_abnormal_lane_cleanup_does_not_depend_on_the_mutable_venv(tmp_path, monkeypatch, stop_failure): + root = tmp_path / "lane-1/run" + with socket.socket() as listener: + listener.bind(("127.0.0.1", 0)) + port = listener.getsockname()[1] + configs = [] + for scenario in ("upgrade", "metadata-loss"): + config = root / scenario / "account/.nanobot/config.json" + config.parent.mkdir(parents=True) + config.write_text(json.dumps({"gateway": {"port": port}, "channels": {"websocket": {"port": port}}})) + configs.append(config) + calls = [] + def stop(command, **kwargs): + calls.append((command, kwargs)) + if stop_failure and len(calls) == 1: + raise subprocess.CalledProcessError(1, command) + monkeypatch.setattr(probe.subprocess, "run", stop) + if stop_failure: + with pytest.raises(RuntimeError, match="bounded cleanup"): + probe.cleanup_lane(root, ["upgrade", "worker-exit", "metadata-loss"]) + else: + probe.cleanup_lane(root, ["upgrade", "worker-exit", "metadata-loss"]) + assert len(calls) == 2 # Still try the second account if the first stop failed. + for (command, options), config in zip(calls, configs, strict=True): + assert command == [sys.executable, "-I", "-B", "-m", "nanobot", "gateway", "stop", "--config", str(config)] + assert options["env"]["HOME"] == str(config.parent.parent) and options["cwd"] == config.parents[2] + assert options["check"] and options["timeout"] == 60 + assert options["stdout"] is options["stderr"] + assert not (root / "managed").exists() + + +@pytest.mark.parametrize("workers", [1, 2]) +def test_serial_dispatch_reports_one_lane_and_checks_original_hash_at_the_end(tmp_path, monkeypatch, workers): + import scripts.build_tui_wheels + + target = wheel(tmp_path, "0.3.6") + monkeypatch.setattr(scripts.build_tui_wheels, "wheel_files", lambda *args, **kwargs: ( + {"nanobot/_build_commit.txt": b"a" * 40}, None, None)) + args = Namespace(wheel=target, baseline_wheel=None, output=tmp_path / "serial", commit="a" * 40, + workers=workers, dock=False, scenario=["upgrade"]) + calls = [] + def serial(args, root, selected, version, original_hash, scenarios, timings): + calls.append(root / "managed") + return [{"scenario": "upgrade"}] + monkeypatch.setattr(probe, "run_serial", serial) + report = probe.run(args) + assert calls == [args.output / "managed"] + assert (report["workers"], report["scenario_count"], report["journey_count"]) == (1, 1, 1) + args.output = tmp_path / "mutated" + def mutate(*args): + target.write_bytes(b"changed target") + return [{"scenario": "upgrade"}] + monkeypatch.setattr(probe, "run_serial", mutate) + with pytest.raises(AssertionError): + probe.run(args) + + +def test_controller_error_does_not_print_exception_values_or_commands(tmp_path): + secret = "temporary-credential-must-not-appear" + target = tmp_path / (secret + ".whl") + result = subprocess.run([sys.executable, "-I", str(Path(probe.__file__).resolve()), "--wheel", str(target), + "--commit", "a" * 40, "--output", str(tmp_path / "evidence")], + capture_output=True, text=True, timeout=10) + assert result.returncode != 0 and "FileNotFoundError" in result.stderr + assert secret not in result.stdout + result.stderr + assert "Traceback" not in result.stderr + + +def test_serial_lanes_install_dependencies_once_and_keep_recovery_chains_on_the_same_venv(tmp_path, monkeypatch): + package = Path(__file__).resolve().parents[1] / "nanobot" + target = wheel(tmp_path, "0.3.6", worker=(package / "update_worker.py").read_bytes(), + fallback=(package / "update_fallback.py").read_bytes()) + original_hash = digest(target) + installations, dependencies, baselines, stages = [], [], [], {} + def execute(command, **options): + if "venv" in command: + installations.append(Path(command[-1])) + Path(command[-1]).mkdir() + elif "pip" in command: + (baselines if "--no-deps" in command else dependencies).append(command[0]) + elif "--phase" in command: + phase = command[command.index("--phase") + 1] + case_root = Path(command[command.index("--output") + 1]) + rows = stages.setdefault(case_root, []) + rows.append((phase, command[0])) + if phase == "prepare": + number = sum(stage == "prepare" for stage, _ in rows) + job = case_root / f"job-{number}" + job.mkdir() + probe.write(case_root / "launch.json", {"directory": str(job), + "command": ["fixture-worker", str(case_root), command[0]]}) + else: + case = probe.read(case_root / "case.json") + restored = case["scenario"] in probe.TWO_JOURNEY_SCENARIOS and case["scenario"] != "upgrade-again" + probe.write(case_root / "result.json", { + **case, "phase": "restored" if restored else "succeeded", + "running_version": case["baseline_version"] if restored else case["target_version"], + }) + elif command[0] == "fixture-worker": + stages[Path(command[1])].append(("worker", command[2])) + elif "gateway" in command: + case_root = Path(command[-1]).parents[2] + stages[case_root].append(("cleanup", command[0])) + else: + pytest.fail("Unexpected verifier subprocess") + monkeypatch.setattr(probe.subprocess, "run", execute) + results = [] + for worker, scenarios in enumerate(probe.scenario_groups(list(probe.SCENARIOS), 2), 1): + root = tmp_path / f"lane-{worker}/run" + root.mkdir(parents=True) + args = Namespace(baseline_wheel=None, commit="a" * 40, dock=False) + results.extend(probe.run_serial(args, root, target, "0.3.6", original_hash, scenarios, + Timings(root / "packaged-update-timings.json"))) + assert len(installations) == len(dependencies) == 2 and len(set(installations)) == 2 + assert len(baselines) == 9 and len(stages) == 9 + assert sum(1 + ("subsequent_update" in result) for result in results) == 15 + assert digest(target) == original_hash + for case_root, rows in stages.items(): + journeys = 1 + (case_root.name in probe.TWO_JOURNEY_SCENARIOS) + assert [stage for stage, _ in rows] == ["prepare", "worker", "verify"] * journeys + ["cleanup"] + interpreters = {python for _, python in rows} + assert len(interpreters) == 1 + assert Path(next(iter(interpreters))).is_relative_to(case_root.parent / "managed") diff --git a/tests/test_update.py b/tests/test_update.py index 6e87a6595..bc01b6817 100644 --- a/tests/test_update.py +++ b/tests/test_update.py @@ -327,14 +327,12 @@ def test_real_python_restart_resolution_detects_cwd_shadowing(tmp_path, monkeypa @pytest.fixture -def installed_release(tmp_path, monkeypatch): +def installed_release(tmp_path, monkeypatch, create_integration_env): """Install a tiny local wheel with real pip, without touching the user's env.""" - import venv import zipfile env = tmp_path / "env" - venv.EnvBuilder(with_pip=True).create(env) - executable = env / ("Scripts/python.exe" if sys.platform == "win32" else "bin/python") + executable = create_integration_env(env) wheels = tmp_path / "wheels" wheels.mkdir() files = { diff --git a/tests/test_update_jobs.py b/tests/test_update_jobs.py index c874de48f..5534c59ed 100644 --- a/tests/test_update_jobs.py +++ b/tests/test_update_jobs.py @@ -11,7 +11,6 @@ import subprocess import sys import threading import time -import venv from dataclasses import replace from pathlib import Path, PureWindowsPath from unittest.mock import AsyncMock @@ -191,7 +190,7 @@ def test_planning_probe_bootstraps_before_target_site(tmp_path, monkeypatch): @pytest.fixture -def installation(tmp_path, monkeypatch, request): +def installation(tmp_path, monkeypatch, request, create_integration_env): # Synthetic local packages are not signed public releases. Approval refusal # is covered through the real feed in test_release_trust.py. monkeypatch.setattr(ReleaseFeed, "_authorize", AsyncMock()) @@ -202,8 +201,7 @@ def installation(tmp_path, monkeypatch, request): artifacts = tmp_path / "artifacts" artifacts.mkdir() environment = tmp_path / "venv with spaces" - venv.EnvBuilder(with_pip=True).create(environment) - python = str(environment / ("Scripts/python.exe" if os.name == "nt" else "bin/python")) + python = str(create_integration_env(environment)) monkeypatch.setenv("PIP_CONFIG_FILE", os.devnull) monkeypatch.setenv("PIP_NO_INDEX", "1") monkeypatch.setenv("PIP_FIND_LINKS", str(artifacts)) diff --git a/webui/playwright.config.ts b/webui/playwright.config.ts index 7e2a27f9c..da6d7f1c5 100644 --- a/webui/playwright.config.ts +++ b/webui/playwright.config.ts @@ -5,7 +5,7 @@ const port = Number(process.env.NANOBOT_BROWSER_TEST_PORT ?? 4178); export default defineConfig({ testDir: "./browser", fullyParallel: false, - workers: 1, + workers: 2, retries: 0, timeout: 30_000, reporter: "list", diff --git a/webui/src/tests/channel-ui-registry.test.ts b/webui/src/tests/channel-ui-registry.test.ts index 573be47e4..48e1d14e7 100644 --- a/webui/src/tests/channel-ui-registry.test.ts +++ b/webui/src/tests/channel-ui-registry.test.ts @@ -1,3 +1,4 @@ +import assert from "node:assert/strict"; import { resolve } from "node:path"; import postcss from "postcss"; @@ -40,7 +41,11 @@ describe("channel UI contributions", () => { vi.stubEnv("NODE_ENV", "production"); try { const config = loadConfig(resolve(process.cwd(), "tailwind.config.js")); - const result = await postcss([tailwindcss(config)]).process("@tailwind utilities;", { from: undefined }); + assert(Array.isArray(config.content)); + // Keep production channel globs and exclusions without rebuilding unrelated app/test CSS. + const content = config.content.filter((entry) => typeof entry === "string" + && (entry.includes("../nanobot/channels/") || entry.startsWith("!"))); + const result = await postcss([tailwindcss({ ...config, content })]).process("@tailwind utilities;", { from: undefined }); // Linear's connecting indicator uses a channel-only arbitrary color. let backgroundColor: string | undefined;