ci: scope native acceptance and bind release candidate artifacts (#6378)
* ci: scope native acceptance and bind release candidate artifacts * ci: isolate Windows installers and use portable Git tree fixtures * test: preserve installer subprocess diagnostics on timeout
This commit is contained in:
1 parent
4dc695ca76
commit
67fc220c8a
15 files changed
+1222
-288
No files matched your search
@@ -0,0 +1,41 @@
|
||||
"""Require success for selected jobs; never confuse a broken selector with no work."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import os
|
||||
|
||||
|
||||
def check_results(needs: dict, event: str) -> list[str]:
|
||||
changes = needs["changes"]
|
||||
if changes["result"] != "success":
|
||||
return ["Change selection did not succeed"]
|
||||
outputs = changes["outputs"]
|
||||
selected = {}
|
||||
for domain in ("python", "webui", "tui", "docker", "native"):
|
||||
value = outputs.get(f"{domain}_required")
|
||||
if value not in ("true", "false"):
|
||||
return [f"Invalid or missing selection: {domain}"]
|
||||
selected[domain] = value == "true"
|
||||
jobs = {"test": selected["python"], "windows_process": selected["python"],
|
||||
"webui_checks": selected["webui"], "webui_browser": selected["webui"],
|
||||
"webui": selected["webui"], "tui": selected["tui"], "docker": selected["docker"],
|
||||
"native": selected["native"] and event != "push",
|
||||
"windows_installers": selected["python"] and selected["native"] and event != "push"}
|
||||
errors = []
|
||||
for job, required in jobs.items():
|
||||
result = needs[job]["result"]
|
||||
if result != "success" and (required or result != "skipped"):
|
||||
errors.append(f"{job}: {'required' if required else 'unselected'}, got {result}")
|
||||
return errors
|
||||
|
||||
|
||||
def main() -> None:
|
||||
errors = check_results(json.loads(os.environ["CHECK_RESULTS"]), os.environ["EVENT_NAME"])
|
||||
if errors:
|
||||
raise SystemExit("\n".join(errors))
|
||||
print("All selected checks passed; other checks were intentionally skipped.")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,168 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Conservative, stdlib-only CI path selection; importable without running git.
|
||||
|
||||
Rules describe validation needs, not event policy: the workflow may restrict native
|
||||
acceptance to PRs, but dispatch and fallback still request every validation lane.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import html
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
import subprocess
|
||||
from fnmatch import fnmatchcase
|
||||
from pathlib import Path
|
||||
|
||||
JOBS = ("python_required", "webui_required", "tui_required", "docker_required", "native_required")
|
||||
ALL = frozenset(JOBS)
|
||||
PYTHON = frozenset({"python_required"})
|
||||
DOCKER = frozenset({"docker_required"})
|
||||
WEBUI = frozenset({"webui_required"})
|
||||
TUI = frozenset({"tui_required"})
|
||||
NATIVE = frozenset({"native_required"})
|
||||
|
||||
# Ordered first-match rules. Keep Docker README inputs before documentation rules,
|
||||
# and embedded channel frontend trees before the Python production catch-all.
|
||||
RULES = (
|
||||
((".github/workflows/ci.yml", ".github/workflows/native-acceptance.yml",
|
||||
"scripts/ci_scope.py", "tests/scripts/test_ci_scope.py",
|
||||
"scripts/native_acceptance_input.py", "tests/scripts/test_native_acceptance_input.py",
|
||||
"scripts/ci_gate.py", "tests/scripts/test_ci_gate.py", "tests/scripts/test_ci_workflows.py"),
|
||||
ALL, "CI selector or execution contract"),
|
||||
((".github/workflows/release-candidate.yml", ".github/workflows/release-approve.yml"),
|
||||
PYTHON | NATIVE, "release workflow (including Python parse/collection validation)"),
|
||||
((".github/workflows/tui-release.yml",), PYTHON | TUI | NATIVE, "native TUI publication workflow"),
|
||||
((".github/workflows/*",), ALL, "unknown workflow"),
|
||||
(("pyproject.toml", "uv.lock", "hatch_build.py", "nanobot/webui/build.py", "scripts/install*",
|
||||
"scripts/build*"), ALL, "cross-domain dependency, build or installation contract"),
|
||||
(("tests/test_docker*.py",), PYTHON | DOCKER, "Docker Python regression tests"),
|
||||
(("Dockerfile", "Dockerfile.*", ".dockerignore", "docker-compose*.yml", "entrypoint.sh",
|
||||
"render-config.json", "README.md", "LICENSE", "THIRD_PARTY_NOTICES.md",
|
||||
"tests/test_docker*", "scripts/docker_compose_smoke.py"), DOCKER, "Docker input or acceptance"),
|
||||
(("docs/*", ".agent/*", ".github/ISSUE_TEMPLATE/*", "AGENTS.md", "CLAUDE.md",
|
||||
"COMMUNICATION.md", "CONTRIBUTING.md", "SECURITY.md", "webui/README.md",
|
||||
"tui/README.md", "render.yaml", "images/*"), frozenset(), "documentation only"),
|
||||
(("scripts/check_client_import_boundaries.*",), WEBUI | TUI, "shared client import boundary checker"),
|
||||
(("packages/client-events/*",), WEBUI | TUI | DOCKER, "shared client event protocol"),
|
||||
(("webui/*", "nanobot/channels/*/webui/*", "nanobot/channels/*/tests/webui/*"),
|
||||
WEBUI | DOCKER, "WebUI source or embedded channel frontend"),
|
||||
(("tui/scripts/package-release.py", "tui/scripts/release-notices.ts", "tui/scripts/prepare-target.ts",
|
||||
"tui/scripts/build.ts", "tui/package.json", "tui/bun.lock"), TUI | NATIVE, "native TUI packaging or dependencies"),
|
||||
(("tui/*",), TUI, "TUI functionality"),
|
||||
(("nanobot/channels/websocket/runtime.py", "nanobot/webui/gateway_endpoint.py"),
|
||||
PYTHON | DOCKER | WEBUI | TUI | NATIVE, "shared gateway lifecycle and client protocol"),
|
||||
# These modules own wire events, transport and session representations used
|
||||
# by both clients. Other backend WebUI modules need only the WebUI consumer.
|
||||
(("nanobot/webui/client_contract.py", "nanobot/webui/outbound_*.py",
|
||||
"nanobot/webui/inbound_commands.py", "nanobot/webui/ws_http.py",
|
||||
"nanobot/webui/gateway_*.py", "nanobot/webui/session_*.py",
|
||||
"nanobot/webui/history.py", "nanobot/webui/transcript.py",
|
||||
"nanobot/webui/sidebar_state.py", "nanobot/webui/settings_*.py",
|
||||
"nanobot/webui/workspaces.py", "nanobot/webui/skills_api.py",
|
||||
"nanobot/webui/cli_apps_api.py", "nanobot/webui/mcp_presets_api.py",
|
||||
"nanobot/webui/recovery.py", "nanobot/webui/forking.py", "nanobot/session/*", "nanobot/events.py",
|
||||
"nanobot/bus/events.py", "nanobot/api/*", "nanobot/channels/websocket/*.py"),
|
||||
PYTHON | DOCKER | WEBUI | TUI, "shared backend client protocol, transport or session representation"),
|
||||
(("nanobot/webui/local_client_assets.py",), PYTHON | DOCKER | WEBUI | NATIVE,
|
||||
"installed client asset discovery"),
|
||||
(("nanobot/webui/*",), PYTHON | DOCKER | WEBUI, "WebUI backend"),
|
||||
(("nanobot/update*", "nanobot/release*", "nanobot/installation*", "nanobot/bun.py",
|
||||
"nanobot/build_info.py", "nanobot/__init__.py", "nanobot/__main__.py",
|
||||
"nanobot/nanobot.py", "nanobot/process_runtime.py", "nanobot/runtime_admission.py", "nanobot/data_access.py",
|
||||
"nanobot/gateway/*", "nanobot/cli/entry.py", "nanobot/cli/commands.py",
|
||||
"nanobot/cli/gateway*.py", "nanobot/cli/update.py", "nanobot/cli/process_identity.py",
|
||||
"nanobot/cli/desktop*.py", "nanobot/cli/tui_launcher.py", "nanobot/cli/dock.py",
|
||||
"nanobot/cli/_macos_dock.py", "nanobot/cli/runtime_config.py", "nanobot/cli/webui.py", "nanobot/cli/webui_support.py",
|
||||
"nanobot/config/paths.py", "nanobot/utils/rotating_output.py",
|
||||
"nanobot/utils/atomic_file.py", "nanobot/utils/file_io.py", "nanobot/utils/runtime.py",
|
||||
"nanobot/utils/restart.py", "nanobot/skills/update-setup/*"),
|
||||
PYTHON | DOCKER | NATIVE, "installed application lifecycle, update or runtime"),
|
||||
(("nanobot/*",), PYTHON | DOCKER, "Python production source"),
|
||||
(("tests/test_update*", "tests/test_windows_update*", "tests/test_release*",
|
||||
"tests/test_install*", "tests/test_packaged_update*", "tests/test_bun.py",
|
||||
"tests/test_build_info.py", "tests/gateway/*", "tests/cli/test_entry.py",
|
||||
"tests/cli/test_commands.py", "tests/cli/test_gateway*", "tests/cli/test_process_identity.py",
|
||||
"tests/cli/test_desktop*", "tests/cli/test_tui*", "tests/cli/test_restart*",
|
||||
"tests/utils/test_atomic*", "tests/utils/test_file_io*", "tests/test_process*",
|
||||
"tests/test_runtime*", "scripts/verify_*", "scripts/release_*",
|
||||
".github/release-signing-requirements.*"), PYTHON | NATIVE, "lifecycle or installed-release verification"),
|
||||
(("tests/*.py", "conftest.py", "scripts/*.py"), PYTHON, "Python tests or tooling"),
|
||||
)
|
||||
|
||||
|
||||
def classify_paths(paths: list[str]) -> dict:
|
||||
"""Select the union of requirements, preserving a reason for every path."""
|
||||
required = set()
|
||||
decisions = []
|
||||
for path in paths:
|
||||
for patterns, jobs, reason in RULES:
|
||||
if any(fnmatchcase(path, pattern) for pattern in patterns):
|
||||
break
|
||||
else:
|
||||
jobs, reason = ALL, "unknown path; conservative full validation"
|
||||
required.update(jobs)
|
||||
decisions.append({"path": path, "reason": reason, "jobs": sorted(jobs)})
|
||||
if not paths:
|
||||
required.update(ALL)
|
||||
return {
|
||||
"outputs": {job: job in required for job in JOBS},
|
||||
"reason": "classified changed paths" if paths else "empty diff; conservative full validation",
|
||||
"paths": decisions,
|
||||
}
|
||||
|
||||
|
||||
def select_scope(event: str, base: str, head: str, *, cwd: Path | None = None) -> dict:
|
||||
"""Use merge-base diff for PRs, endpoint diff for pushes, full for dispatch."""
|
||||
if event == "workflow_dispatch":
|
||||
result = classify_paths([])
|
||||
result["reason"] = "manual dispatch; full validation"
|
||||
return result
|
||||
if event not in {"pull_request", "push"}:
|
||||
raise ValueError(f"unsupported event: {event}")
|
||||
# Accept only commit IDs, never option-like revision expressions from env.
|
||||
if not all(re.fullmatch(r"[0-9a-fA-F]{40}|[0-9a-fA-F]{64}", sha) for sha in (base, head)):
|
||||
result = classify_paths([])
|
||||
result["reason"] = "invalid or missing commit SHA; conservative full validation"
|
||||
return result
|
||||
diff_range = f"{base}{'...' if event == 'pull_request' else '..'}{head}"
|
||||
try:
|
||||
diff = subprocess.run(
|
||||
["git", "diff", "--name-only", "--no-renames", "-z", diff_range, "--"],
|
||||
cwd=cwd, check=True, capture_output=True, timeout=60,
|
||||
)
|
||||
except (OSError, subprocess.SubprocessError) as exc:
|
||||
result = classify_paths([])
|
||||
result["reason"] = f"git diff unavailable ({type(exc).__name__}); conservative full validation"
|
||||
return result
|
||||
paths = diff.stdout.decode("utf-8", errors="surrogateescape").split("\0")
|
||||
result = classify_paths([path for path in paths if path])
|
||||
result["diff_range"] = diff_range
|
||||
return result
|
||||
|
||||
|
||||
def main() -> int:
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument("--event", required=True, choices=("pull_request", "push", "workflow_dispatch"))
|
||||
parser.add_argument("--base", default="")
|
||||
parser.add_argument("--head", default="")
|
||||
args = parser.parse_args()
|
||||
result = select_scope(args.event, args.base, args.head)
|
||||
report = json.dumps(result, indent=2, ensure_ascii=True)
|
||||
print(report)
|
||||
if output := os.environ.get("GITHUB_OUTPUT"):
|
||||
with open(output, "a", encoding="utf-8") as stream:
|
||||
for job, required in result["outputs"].items():
|
||||
stream.write(f"{job}={str(required).lower()}\n")
|
||||
if summary := os.environ.get("GITHUB_STEP_SUMMARY"):
|
||||
with open(summary, "a", encoding="utf-8") as stream:
|
||||
# JSON escapes path newlines; HTML escaping also prevents Markdown or
|
||||
# raw HTML in filenames from escaping the summary's preformatted block.
|
||||
stream.write("## CI scope\n\n<pre>" + html.escape(report) + "</pre>\n")
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
@@ -0,0 +1,70 @@
|
||||
"""Bind native acceptance to the exact wheel produced by this workflow run."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
import subprocess
|
||||
import tomllib
|
||||
from pathlib import Path
|
||||
from zipfile import ZipFile
|
||||
|
||||
|
||||
def acceptance_input(directory: Path, *, tag: str, commit: str,
|
||||
manifest_sha256: str = "", version: str = "") -> dict[str, str]:
|
||||
if not re.fullmatch(r"[0-9a-f]{40}", commit):
|
||||
raise ValueError("Acceptance requires an exact candidate commit")
|
||||
if manifest_sha256:
|
||||
manifest_bytes = (directory / "release-manifest.json").read_bytes()
|
||||
if hashlib.sha256(manifest_bytes).hexdigest() != manifest_sha256:
|
||||
raise ValueError("Candidate manifest differs from the build output")
|
||||
manifest = json.loads(manifest_bytes)
|
||||
if manifest["candidate_commit"] != commit:
|
||||
raise ValueError("Candidate commit differs from the build output")
|
||||
version = manifest["version"]
|
||||
if not re.fullmatch(r"[0-9][A-Za-z0-9.]*", version):
|
||||
raise ValueError("Invalid acceptance version")
|
||||
filename = f"nanobot_ai-{version}-py3-none-{tag}.whl"
|
||||
wheel = directory / filename
|
||||
if wheel.is_symlink() or not wheel.is_file():
|
||||
raise ValueError("Acceptance requires the exact native wheel")
|
||||
with wheel.open("rb") as stream:
|
||||
sha256 = hashlib.file_digest(stream, "sha256").hexdigest()
|
||||
if manifest_sha256:
|
||||
records = [item for item in manifest["artifacts"] if item["filename"] == filename]
|
||||
if len(records) != 1 or (records[0]["sha256"], records[0]["size"]) != (sha256, wheel.stat().st_size):
|
||||
raise ValueError("Candidate wheel differs from its manifest")
|
||||
with ZipFile(wheel) as archive:
|
||||
if archive.read("nanobot/_build_commit.txt").decode().strip() != commit:
|
||||
raise ValueError("Wheel build commit differs from the acceptance target")
|
||||
return {"wheel": str(wheel.resolve()), "version": version, "commit": commit,
|
||||
"wheel_sha256": sha256, "manifest_sha256": manifest_sha256}
|
||||
|
||||
|
||||
def main() -> None:
|
||||
root = Path(os.environ["RUNNER_TEMP"])
|
||||
candidate = os.environ["CANDIDATE"] == "true"
|
||||
if candidate:
|
||||
commit = os.environ["EXPECTED_COMMIT"]
|
||||
manifest_sha256 = os.environ["EXPECTED_MANIFEST"]
|
||||
if not re.fullmatch(r"[0-9a-f]{64}", manifest_sha256):
|
||||
raise ValueError("Candidate acceptance requires the build's manifest hash")
|
||||
version = ""
|
||||
else:
|
||||
commit = subprocess.check_output(["git", "rev-parse", "HEAD"], text=True).strip()
|
||||
manifest_sha256 = ""
|
||||
version = tomllib.loads(Path("pyproject.toml").read_text(encoding="utf-8"))["project"]["version"]
|
||||
record = acceptance_input(root / "native-wheel", tag=os.environ["WHEEL_TAG"], commit=commit,
|
||||
manifest_sha256=manifest_sha256, version=version)
|
||||
(root / "native-input.json").write_text(json.dumps(record, indent=2) + "\n", encoding="utf-8")
|
||||
with Path(os.environ["GITHUB_ENV"]).open("a", encoding="utf-8") as stream:
|
||||
for key in ("wheel", "version", "commit"):
|
||||
if "\n" in record[key] or "\r" in record[key]:
|
||||
raise ValueError("Invalid acceptance environment value")
|
||||
stream.write(f"ACCEPTANCE_{key.upper()}={record[key]}\n")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -26,7 +26,7 @@ import sqlite3
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
from contextlib import closing
|
||||
from contextlib import closing, contextmanager
|
||||
from pathlib import Path
|
||||
from unittest.mock import patch
|
||||
from urllib.parse import quote
|
||||
@@ -49,6 +49,35 @@ def write(path: Path, value) -> None:
|
||||
path.write_text(json.dumps(value, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")
|
||||
|
||||
|
||||
class Timings:
|
||||
"""Separate, incrementally persisted evidence; never include commands or logs."""
|
||||
|
||||
def __init__(self, output: Path):
|
||||
self.output = output
|
||||
self.records: list[dict] = []
|
||||
|
||||
@contextmanager
|
||||
def measure(self, phase: str, *, scenario: str | None = None, journey: int | None = None):
|
||||
started = time.perf_counter()
|
||||
succeeded = False
|
||||
try:
|
||||
yield
|
||||
succeeded = True
|
||||
finally:
|
||||
record = {"phase": phase, "scenario": scenario, "journey": journey,
|
||||
"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)
|
||||
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 replace_once(source: bytes, old: bytes, new: bytes) -> bytes:
|
||||
if source.count(old) != 1:
|
||||
raise ValueError("The fault-injection seam changed; review the acceptance fixture")
|
||||
@@ -612,6 +641,7 @@ def run(args) -> dict:
|
||||
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
|
||||
@@ -635,103 +665,117 @@ def run(args) -> dict:
|
||||
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.
|
||||
subprocess.run([sys.executable, "-I", "-m", "venv", str(environment)], check=True, env=system, timeout=90)
|
||||
subprocess.run([str(python), "-I", "-m", "pip", "install", "--only-binary=:all:", str(target)],
|
||||
check=True, env=system, timeout=600, stdout=subprocess.DEVNULL)
|
||||
with timings.measure("venv"):
|
||||
subprocess.run([sys.executable, "-I", "-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:
|
||||
case_root = root / scenario
|
||||
case_root.mkdir()
|
||||
account = case_root / "account"
|
||||
account.mkdir()
|
||||
env = dict(system, HOME=str(account), USERPROFILE=str(account), APPDATA=str(account / "config"),
|
||||
LOCALAPPDATA=str(account / "data"), XDG_CONFIG_HOME=str(account / "config"),
|
||||
XDG_CACHE_HOME=str(root / "cache"), XDG_DATA_HOME=str(account / "data"),
|
||||
TMPDIR=str(case_root), TMP=str(case_root), TEMP=str(case_root))
|
||||
selected = target
|
||||
feed = case_root / "feed.json"
|
||||
if scenario in {"upgrade-again", "import-failure", "restart-failure", "restore-interruption"}:
|
||||
intermediate = Version(version).base_version + ".dev0"
|
||||
if not Version(baseline_version) < Version(intermediate) < Version(version):
|
||||
raise ValueError("Consecutive updates require baseline < target.dev0 < target")
|
||||
# Faults and the instrumented intermediate get a distinct version:
|
||||
# never overwrite a previously observed version with healthy bytes.
|
||||
selected = fixture_wheel(target, case_root / "intermediate", intermediate,
|
||||
feed=feed if scenario == "upgrade-again" else None, scenario=scenario)
|
||||
write(feed, feed_records(selected, args.commit))
|
||||
earlier = baseline_version
|
||||
if scenario == "skipped-preview" and not args.baseline_wheel:
|
||||
earlier = Version(version).base_version + ".dev0"
|
||||
if Version(earlier) >= Version(version):
|
||||
raise ValueError("Skipped Preview requires a target newer than dev0")
|
||||
baseline = fixture_wheel(baseline_source, case_root / "baseline", earlier, feed=feed, scenario=scenario)
|
||||
case = {"scenario": scenario, "baseline_version": earlier, "dock": args.dock,
|
||||
"target_version": str(parse_wheel_filename(selected.name)[1]),
|
||||
"baseline_kind": "instrumented historical wheel" if args.baseline_wheel else "instrumented version fixture",
|
||||
"baseline_source_sha256": digest(baseline_source), "baseline_fixture_sha256": digest(baseline),
|
||||
"target_wheel": str(selected), "target_sha256": digest(selected), "commit": args.commit,
|
||||
"target_unmodified": selected == target}
|
||||
write(case_root / "case.json", case)
|
||||
subprocess.run([str(python), "-I", "-m", "pip", "install", "--no-deps", "--force-reinstall", str(baseline)],
|
||||
check=True, env=env, timeout=120, stdout=subprocess.DEVNULL)
|
||||
child = [str(python), "-I", str(Path(__file__).resolve())]
|
||||
with (case_root / "acceptance.log").open("w", encoding="utf-8") as log:
|
||||
def journey():
|
||||
subprocess.run([*child, "--phase", "prepare", "--output", str(case_root)],
|
||||
check=True, env=env, cwd=case_root, stdout=log, stderr=log, timeout=180)
|
||||
launch = read(case_root / "launch.json")
|
||||
subprocess.run(launch["command"], check=True, env=env, cwd=launch["directory"],
|
||||
stdout=log, stderr=log, timeout=420)
|
||||
subprocess.run([*child, "--phase", "verify", "--output", str(case_root)],
|
||||
check=True, env=env, cwd=case_root, stdout=log, stderr=log, timeout=180)
|
||||
return read(case_root / "result.json")
|
||||
with timings.measure("scenario_total", scenario=scenario):
|
||||
with timings.measure("fixture", scenario=scenario, journey=1):
|
||||
case_root = root / scenario
|
||||
case_root.mkdir()
|
||||
account = case_root / "account"
|
||||
account.mkdir()
|
||||
env = dict(system, HOME=str(account), USERPROFILE=str(account), APPDATA=str(account / "config"),
|
||||
LOCALAPPDATA=str(account / "data"), XDG_CONFIG_HOME=str(account / "config"),
|
||||
XDG_CACHE_HOME=str(root / "cache"), XDG_DATA_HOME=str(account / "data"),
|
||||
TMPDIR=str(case_root), TMP=str(case_root), TEMP=str(case_root))
|
||||
selected = target
|
||||
feed = case_root / "feed.json"
|
||||
if scenario in {"upgrade-again", "import-failure", "restart-failure", "restore-interruption"}:
|
||||
intermediate = Version(version).base_version + ".dev0"
|
||||
if not Version(baseline_version) < Version(intermediate) < Version(version):
|
||||
raise ValueError("Consecutive updates require baseline < target.dev0 < target")
|
||||
# Faults and the instrumented intermediate get a distinct version:
|
||||
# never overwrite a previously observed version with healthy bytes.
|
||||
selected = fixture_wheel(target, case_root / "intermediate", intermediate,
|
||||
feed=feed if scenario == "upgrade-again" else None, scenario=scenario)
|
||||
write(feed, feed_records(selected, args.commit))
|
||||
earlier = baseline_version
|
||||
if scenario == "skipped-preview" and not args.baseline_wheel:
|
||||
earlier = Version(version).base_version + ".dev0"
|
||||
if Version(earlier) >= Version(version):
|
||||
raise ValueError("Skipped Preview requires a target newer than dev0")
|
||||
baseline = fixture_wheel(baseline_source, case_root / "baseline", earlier, feed=feed, scenario=scenario)
|
||||
case = {"scenario": scenario, "baseline_version": earlier, "dock": args.dock,
|
||||
"target_version": str(parse_wheel_filename(selected.name)[1]),
|
||||
"baseline_kind": "instrumented historical wheel" if args.baseline_wheel else "instrumented version fixture",
|
||||
"baseline_source_sha256": digest(baseline_source), "baseline_fixture_sha256": digest(baseline),
|
||||
"target_wheel": str(selected), "target_sha256": digest(selected), "commit": args.commit,
|
||||
"target_unmodified": selected == target}
|
||||
write(case_root / "case.json", case)
|
||||
with timings.measure("baseline_install", scenario=scenario, journey=1):
|
||||
subprocess.run([str(python), "-I", "-m", "pip", "install", "--no-deps", "--force-reinstall", str(baseline)],
|
||||
check=True, env=env, timeout=120, stdout=subprocess.DEVNULL)
|
||||
child = [str(python), "-I", str(Path(__file__).resolve())]
|
||||
# Raw logs stay private to this local evidence root, including on success.
|
||||
with (case_root / "acceptance.log").open("w", encoding="utf-8") as log:
|
||||
def journey(number):
|
||||
with timings.measure("prepare", scenario=scenario, journey=number):
|
||||
subprocess.run([*child, "--phase", "prepare", "--output", str(case_root)],
|
||||
check=True, env=env, cwd=case_root, stdout=log, stderr=log, timeout=180)
|
||||
launch = read(case_root / "launch.json")
|
||||
with timings.measure("worker", scenario=scenario, journey=number):
|
||||
subprocess.run(launch["command"], check=True, env=env, cwd=launch["directory"],
|
||||
stdout=log, stderr=log, timeout=420)
|
||||
with timings.measure("verify", scenario=scenario, journey=number):
|
||||
subprocess.run([*child, "--phase", "verify", "--output", str(case_root)],
|
||||
check=True, env=env, cwd=case_root, stdout=log, stderr=log, timeout=180)
|
||||
return read(case_root / "result.json")
|
||||
|
||||
try:
|
||||
result = journey()
|
||||
if result["phase"] == "restored" or scenario == "upgrade-again":
|
||||
previous_job = read(case_root / "launch.json")["directory"]
|
||||
write(feed, feed_records(target, args.commit, generation=2))
|
||||
write(case_root / "case.json", {
|
||||
**case, "scenario": "upgrade", "baseline_version": result["running_version"],
|
||||
"baseline_kind": "previous journey's running installation",
|
||||
"baseline_source_sha256": (case["baseline_source_sha256"] if result["phase"] == "restored"
|
||||
else case["target_sha256"]),
|
||||
"baseline_fixture_sha256": (case["baseline_fixture_sha256"] if result["phase"] == "restored"
|
||||
else case["target_sha256"]),
|
||||
"target_version": version, "target_wheel": str(target),
|
||||
"target_sha256": original_hash, "target_unmodified": True,
|
||||
})
|
||||
result["subsequent_update"] = journey()
|
||||
assert read(case_root / "launch.json")["directory"] != previous_job
|
||||
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:
|
||||
subprocess.run([str(python), "-I", "-m", "nanobot", "gateway", "stop", "--config",
|
||||
str(account / ".nanobot/config.json")], env=env, cwd=case_root,
|
||||
stdout=log, stderr=log, timeout=60, check=True)
|
||||
config_file = account / ".nanobot/config.json"
|
||||
if config_file.exists():
|
||||
config = read(config_file)
|
||||
_wait_for_closed_listeners((config["gateway"]["port"], config["channels"]["websocket"]["port"]))
|
||||
results[-1]["gateway_process_stopped"] = True
|
||||
dock_address = results[-1].get("dock_socket")
|
||||
if not dock_address:
|
||||
dock_address = results[-1].get("subsequent_update", {}).get("dock_socket")
|
||||
if dock_address:
|
||||
_wait_dock(Path(dock_address), present=False)
|
||||
results[-1]["dock_stopped"] = True
|
||||
print(f"PASS {scenario}: {results[-1]['phase']}", flush=True)
|
||||
try:
|
||||
result = journey(1)
|
||||
if result["phase"] == "restored" or scenario == "upgrade-again":
|
||||
with timings.measure("fixture", scenario=scenario, journey=2):
|
||||
previous_job = read(case_root / "launch.json")["directory"]
|
||||
write(feed, feed_records(target, args.commit, generation=2))
|
||||
write(case_root / "case.json", {
|
||||
**case, "scenario": "upgrade", "baseline_version": result["running_version"],
|
||||
"baseline_kind": "previous journey's running installation",
|
||||
"baseline_source_sha256": (case["baseline_source_sha256"] if result["phase"] == "restored"
|
||||
else case["target_sha256"]),
|
||||
"baseline_fixture_sha256": (case["baseline_fixture_sha256"] if result["phase"] == "restored"
|
||||
else case["target_sha256"]),
|
||||
"target_version": version, "target_wheel": str(target),
|
||||
"target_sha256": original_hash, "target_unmodified": True,
|
||||
})
|
||||
result["subsequent_update"] = journey(2)
|
||||
assert read(case_root / "launch.json")["directory"] != previous_job
|
||||
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",
|
||||
str(account / ".nanobot/config.json")], env=env, cwd=case_root,
|
||||
stdout=log, stderr=log, timeout=60, check=True)
|
||||
config_file = account / ".nanobot/config.json"
|
||||
if config_file.exists():
|
||||
config = read(config_file)
|
||||
_wait_for_closed_listeners((config["gateway"]["port"], config["channels"]["websocket"]["port"]))
|
||||
# No journey result exists on failure; successful journeys
|
||||
# also retain the existing native Dock shutdown assertion.
|
||||
if results and results[-1]["scenario"] == scenario:
|
||||
results[-1]["gateway_process_stopped"] = True
|
||||
dock_address = results[-1].get("dock_socket")
|
||||
if not dock_address:
|
||||
dock_address = results[-1].get("subsequent_update", {}).get("dock_socket")
|
||||
if dock_address:
|
||||
_wait_dock(Path(dock_address), present=False)
|
||||
results[-1]["dock_stopped"] = True
|
||||
print(f"PASS {scenario}: {results[-1]['phase']}", flush=True)
|
||||
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,
|
||||
|
||||
Reference in new issue
Block a user