From 0c336e2b59fa61da01f7056373f9128aaf4a1941 Mon Sep 17 00:00:00 2001 From: Jhin Lee Date: Sat, 7 Nov 2026 07:22:22 -0500 Subject: [PATCH] Make upstream release detection manual and remove runner download diagnostic --- .github/workflows/auto_upstream_release.yml | 4 +- .../workflows/runner_download_diagnostic.yml | 34 -- .github/workflows/validate.yml | 2 +- README.md | 2 +- diagnostics/README.md | 81 +--- diagnostics/runner_downloads.py | 360 ------------------ diagnostics/test_runner_downloads.py | 234 ------------ docs/release_protocol.md | 4 +- tools/qualification_scope.py | 2 +- tools/test_release_version_policy.py | 4 +- 10 files changed, 10 insertions(+), 717 deletions(-) delete mode 100644 .github/workflows/runner_download_diagnostic.yml delete mode 100644 diagnostics/runner_downloads.py delete mode 100644 diagnostics/test_runner_downloads.py diff --git a/.github/workflows/auto_upstream_release.yml b/.github/workflows/auto_upstream_release.yml index 74b28cd..6b9df90 100644 --- a/.github/workflows/auto_upstream_release.yml +++ b/.github/workflows/auto_upstream_release.yml @@ -1,8 +1,6 @@ name: Detect Upstream Release on: - schedule: - - cron: "17 6 * * *" workflow_dispatch: permissions: @@ -57,7 +55,7 @@ jobs: print(f"Reason: `{result['reason']}`") print(f"Preparation available: `{str(result['shouldPrepare']).lower()}`") print() - print("This scheduled workflow never dispatches a build and never publishes.") + print("This manually dispatched workflow never dispatches a build and never publishes.") if result["shouldPrepare"]: preparation = result["preparation"] print("A maintainer or central llamadart orchestration may use the exact inputs:") diff --git a/.github/workflows/runner_download_diagnostic.yml b/.github/workflows/runner_download_diagnostic.yml deleted file mode 100644 index d03d398..0000000 --- a/.github/workflows/runner_download_diagnostic.yml +++ /dev/null @@ -1,34 +0,0 @@ -name: Runner Download Diagnostic - -on: - workflow_dispatch: - -permissions: - contents: read - -jobs: - diagnose: - name: Downloads (${{ matrix.os }}) - runs-on: ${{ matrix.os }} - timeout-minutes: 17 - strategy: - fail-fast: false - matrix: - os: [windows-latest, ubuntu-latest, ubuntu-24.04-arm, macos-latest] - steps: - - uses: actions/checkout@v6 - with: - persist-credentials: false - - uses: actions/setup-node@v4 - with: - node-version: "24" - - name: Sample exact acquisition paths three times - run: python diagnostics/runner_downloads.py - - name: Retain sanitized diagnostic reports - if: always() - uses: actions/upload-artifact@v4 - with: - name: download-diagnostic-${{ matrix.os }} - path: diagnostic-results/*.json - if-no-files-found: warn - retention-days: 7 diff --git a/.github/workflows/validate.yml b/.github/workflows/validate.yml index 369c649..4ad7160 100644 --- a/.github/workflows/validate.yml +++ b/.github/workflows/validate.yml @@ -95,7 +95,7 @@ jobs: --output /tmp/schema2_contract_manifest.json cmp tools/fixtures/schema2_contract_manifest.json \ /tmp/schema2_contract_manifest.json - - name: Validate download diagnostic contracts + - name: Validate diagnostic contracts run: python3 -m unittest discover -s diagnostics -p 'test_*.py' - name: Web scaffold self-test run: node web/src/index.js --self-test diff --git a/README.md b/README.md index 8ae257d..dfeed2b 100644 --- a/README.md +++ b/README.md @@ -142,7 +142,7 @@ python3 tools/validate_artifacts.py transaction and exits without mutation. Draft recovery is restricted to a rerun of the original workflow run, so a new dispatch cannot replace another run's partial assets. -- `Detect Upstream Release`: runs daily with read-only permissions. It detects +- `Detect Upstream Release`: is dispatched manually, with read-only permissions. It detects and records a consumable stable candidate as `preparation.json`; it never dispatches the build and never publishes. diff --git a/diagnostics/README.md b/diagnostics/README.md index 70b938d..4abcddd 100644 --- a/diagnostics/README.md +++ b/diagnostics/README.md @@ -1,83 +1,4 @@ # Diagnostics For the explicit Qwen3 model repair, see -[Qwen3 tokenizer repair](../docs/qwen3_tokenizer_repair.md). It is separate from -the runner download workflow below and is never run automatically. - -# Runner download diagnostic - -This manual-only workflow screens the acquisition failures observed in native -release run `34856149932`, attempts 1 and 2, at native commit -`deef59818b0514c54929d7215c10ed6cba3b0f63` and upstream commit -`e9fd8c53ff968071774206163027dd84bedfe925`. It does not repair a demonstrated -transport defect, publish anything, qualify runtime artifacts or authorize a -publication retry. It does not modify successful attempt-2 artifacts. - -The workflow must first be reviewed and merged onto the default branch to become -available for a separately authorized `workflow_dispatch`. It runs on Windows x64, -Ubuntu x64/arm64 and macOS arm64, covering the affected host/network classes. -There are no inputs, production build commands, release permissions, secrets, -mirrors, settings changes or model downloads. - -## Samples and bounds - -Each runner starts three independent rounds at approximately 0, 300 and 600 -seconds. Each round has a 240-second process-tree deadline; the workflow job has a -17-minute deadline. Temporary npm, Bazelisk, Bazel output and repository caches -are new each round. Bazel runs in batch mode and ignores user rc files. - -Each round gives the production Python downloader a separate 45-second outer -deadline to download the small pinned rules_shell archive. Its original urllib -User-Agent, redirects, 60-second socket timeout and three-attempt retry policy -remain intact inside that diagnostic deadline. The body is capped at 2 MiB per -attempt; a complete successful body must match the existing upstream SHA-256. -This complete small-archive check does not download or verify the full large -LiteRT-LM source archive. - -Next, pinned npm package `@bazel/bazelisk@1.28.1` acquires/selects Bazel 7.6.1 with a -75-second outer deadline. A separate 60-second Bazel `query` fetches only a minimal -`http_archive` using the exact rules_shell URL and SHA-256; its empty filegroup -has no native target or dependency fanout. The fresh repository cache must contain -exactly one archive, independently matching the small pinned checksum and size -bound. This exercises Bazelisk and Bazel's -actual HTTP stacks. It does not claim the historical runners used Bazelisk -1.28.1: their exact bootstrap version was not recorded. npm acquisition is an -additional diagnostic prerequisite and can fail independently. - -Finally, four concurrent urllib workers GET the exact failed source, host Bazel -binary and dependency URLs. Each response is limited to 64 KiB, with a 10-second -socket timeout. Eight URLs means at most 512 KiB of sampled response bodies per -round. HTTP 200 plus the expected gzip, ELF, Mach-O or PE prefix is screening -only, not full-body integrity or actual Bazel-client reproduction. Redirects can -consume additional time, so the outer deadline remains authoritative. - -The managed clients do not expose a body-byte limit for Bazel/npm acquisition; -they are bounded here by one bootstrap plus one query per round, fresh disposable -caches and process deadlines. No claim of a strict network-byte cap is made for -those clients. A deadline, failed acquisition, missing sample or checksum failure -makes the diagnostic incomplete/failed; it must not count as recovery evidence. -Three passing rounds are operational evidence, not a guarantee the next release -run will succeed. All existing build, checksum, provenance and model gates remain -authoritative. - -## Retained evidence and local checks - -Only `diagnostic-results/*.json` is uploaded, for seven days. Reports separate the -investigated release identities from the current diagnostic workflow SHA/run ID/ -attempt. They contain sanitized redirect host/path, allowlisted HTTP status, -request IDs, cache/Retry-After metadata where available, durations, body bounds, -checksums and client results. Raw client logs, exceptions, headers, signed query -strings, credentials and temporary caches are never uploaded or printed. - -Run the offline contract tests with: - -```sh -python3 -m unittest discover -s diagnostics -p 'test_*.py' -``` - -A separately authorized local one-round check can use -`python3 diagnostics/runner_downloads.py --round-report /tmp/download-round.json`. -It is local evidence, not runner evidence. Running the script without arguments -uses the three-round schedule. Diagnostic-only changes do not trigger the -full-platform PR qualification workflow; the existing Validate job runs these -lightweight tests. +[Qwen3 tokenizer repair](../docs/qwen3_tokenizer_repair.md). It is never run automatically. diff --git a/diagnostics/runner_downloads.py b/diagnostics/runner_downloads.py deleted file mode 100644 index 6f1dd73..0000000 --- a/diagnostics/runner_downloads.py +++ /dev/null @@ -1,360 +0,0 @@ -"""Bounded, read-only acquisition screening; never a release qualification gate.""" -from __future__ import annotations - -import argparse -import contextlib -from concurrent.futures import ThreadPoolExecutor -from datetime import datetime, timezone -import hashlib -import io -import json -import os -from pathlib import Path -import platform -import re -import shutil -import signal -import subprocess -import sys -import tempfile -import time -import urllib.error -import urllib.parse -import urllib.request -from unittest.mock import patch - -ROOT = Path(__file__).resolve().parents[1] -UPSTREAM = "e9fd8c53ff968071774206163027dd84bedfe925" -INVESTIGATION = {"nativeCommit": "deef59818b0514c54929d7215c10ed6cba3b0f63", "upstreamCommit": UPSTREAM, - "runId": "34856149932", "correlationId": "litert-v017-deef598-20260914-retry1"} -BAZEL_VERSION = "7.6.1" -BAZELISK_PACKAGE = "@bazel/bazelisk@1.28.1" -USER_AGENT = "litert-lm-native-build" -ROUNDS = 3 -INTERVAL_SECONDS = 300 -ROUND_SECONDS = 240 -PREFIX_BYTES = 64 * 1024 -SMALL_ARCHIVE_BYTES = 2 * 1024 * 1024 -RULES_URL = "https://github.com/bazelbuild/rules_shell/releases/download/v0.4.1/rules_shell-v0.4.1.tar.gz" -RULES_SHA256 = "bc61ef94facc78e20a645726f64756e5e285a045037c7a61f65af2941f4c25e1" -URLS = { - "owner_source": f"https://github.com/google-ai-edge/LiteRT-LM/archive/{UPSTREAM}.tar.gz", - "litert_source": "https://github.com/google-ai-edge/LiteRT/archive/9fe5be45564c868408e6514c8aabb83e211a0911.tar.gz", - "rules_shell": RULES_URL, - "rules_apple": "https://github.com/bazelbuild/rules_apple/releases/download/3.22.0/rules_apple.3.22.0.tar.gz", - "rules_swift": "https://github.com/bazelbuild/rules_swift/releases/download/2.9.0/rules_swift.2.9.0.tar.gz", - "rules_ml_toolchain": "https://github.com/google-ml-infra/rules_ml_toolchain/archive/2eddbc595cc0bbe650c2640204f66b14f015f1a8.tar.gz", - "abseil": "https://github.com/abseil/abseil-cpp/archive/20260526.0.tar.gz", -} - - -def safe_url(value: str) -> str: - parsed = urllib.parse.urlsplit(value) - # Deliberately omit userinfo, query, fragment and all unrecognized hosts. - host = parsed.hostname or "" - if host not in {"github.com", "codeload.github.com", "release-assets.githubusercontent.com"}: - return "[other-host]" - return f"https://{host}{parsed.path}" - - -def response_metadata(response) -> dict: - result = {"status": response.code, "url": safe_url(response.url)} - retry = response.headers.get("Retry-After", "") - if retry.isdecimal() and len(retry) <= 8: - result["retryAfterSeconds"] = int(retry) - # Do not retain arbitrary server header text, cookies, auth or signed URLs. - for header in ("X-GitHub-Request-Id", "X-Ms-Request-Id"): - value = response.headers.get(header, "") - if value and len(value) <= 80 and all(c in "0123456789abcdefABCDEF:-" for c in value): - result[header] = value - cache = response.headers.get("X-Cache", "").upper() - if cache in {"HIT", "MISS", "HIT, HIT", "MISS, HIT"}: - result["cache"] = cache - return result - - -class Redirects(urllib.request.HTTPRedirectHandler): - def __init__(self, records: list): - self.records = records - - def redirect_request(self, request, response, code, message, headers, new_url): - self.records.append({"status": code, "from": safe_url(request.full_url), "to": safe_url(new_url)}) - return super().redirect_request(request, response, code, message, headers, new_url) - - -def screen(url: str) -> dict: - records: list = [] - start = time.monotonic() - result = {"scope": "bounded GET only; not complete artifact verification", "client": "urllib", "redirects": records} - try: - opener = urllib.request.build_opener(Redirects(records)) - request = urllib.request.Request(url, headers={"User-Agent": USER_AGENT}) - with opener.open(request, timeout=10) as response: - result.update(response_metadata(response)) - body = response.read(PREFIX_BYTES) - expected_prefix = b"MZ" if url.endswith(".exe") else b"\x7fELF" if "bazel-7.6.1-linux-" in url else b"\xcf\xfa\xed\xfe" if "bazel-7.6.1-darwin-" in url else b"\x1f\x8b" - result.update(bytesRead=len(body), prefixHex=body[:4].hex(), result="pass" if response.code == 200 and body.startswith(expected_prefix) else "fail") - except urllib.error.HTTPError as error: - result.update(response_metadata(error), result="fail", error="http") - error.close() - except Exception: - result.update(result="fail", error="transport") - result["seconds"] = round(time.monotonic() - start, 3) - return result - - -class LimitedResponse: - def __init__(self, response): - self.response = response - self.total = 0 - - def __enter__(self): - return self - - def __exit__(self, *args): - self.response.close() - - def read(self, size: int) -> bytes: - body = self.response.read(min(size, SMALL_ARCHIVE_BYTES + 1 - self.total)) - self.total += len(body) - if self.total > SMALL_ARCHIVE_BYTES: - raise ValueError("Small archive byte bound exceeded") - return body - - -def verify_checksum(path: Path) -> None: - if hashlib.sha256(path.read_bytes()).hexdigest() != RULES_SHA256: - raise ValueError("Pinned checksum mismatch") - - -def owner_download(directory: Path) -> dict: - start = time.monotonic() - # Invoke the existing production downloader without changing its retries, - # timeout, User-Agent or redirect semantics; only cap diagnostic body size. - sys.path.insert(0, str(ROOT / "tools")) - from download_utils import download_to_path - records: list = [] - opener = urllib.request.build_opener(Redirects(records)) - output = directory / "rules_shell.tar.gz" - result = {"client": "production download_utils.download_to_path", "scope": "complete checksum-pinned small archive", "redirects": records} - def open_bounded(request, timeout): - try: - response = opener.open(request, timeout=timeout) - result["lastResponse"] = response_metadata(response) - return LimitedResponse(response) - except urllib.error.HTTPError as error: - result["lastResponse"] = response_metadata(error) - error.close() - raise - try: - # Raw client exceptions/logs may contain signed URLs: never retain them. - with contextlib.redirect_stderr(io.StringIO()), patch.object(urllib.request, "urlopen", side_effect=open_bounded): - download_to_path(RULES_URL, output, headers={"User-Agent": USER_AGENT}, label="pinned rules_shell") - try: - verify_checksum(output) - except ValueError: - result.update(result="fail", error="checksum_mismatch") - else: - result.update(result="pass", sha256=RULES_SHA256, bytesRead=output.stat().st_size) - except Exception: - result.update(result="fail", error="http" if result.get("lastResponse", {}).get("status", 0) >= 400 else "transport_or_size_bound") - result["seconds"] = round(time.monotonic() - start, 3) - return result - - -def kill_tree(process: subprocess.Popen) -> None: - if os.name == "nt": - subprocess.run(["taskkill", "/PID", str(process.pid), "/T", "/F"], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, check=False) - else: - # Nested acquisition clients may start their own process groups. Kill - # descendants as well as the worker so a deadline leaves no Bazel server. - listing = subprocess.check_output(["ps", "-eo", "pid=,ppid="], text=True) - parents = {int(pid): int(parent) for pid, parent in (line.split() for line in listing.splitlines())} - descendants = [process.pid] - for parent in descendants: - descendants.extend(pid for pid, ppid in parents.items() if ppid == parent and pid not in descendants) - for pid in reversed(descendants): - try: - os.kill(pid, signal.SIGKILL) - except ProcessLookupError: - pass - process.wait() - - -def command(command: list[str], directory: Path, env: dict, seconds: int) -> dict: - start = time.monotonic() - # Capture only in memory, never upload or print raw client diagnostics. - process = subprocess.Popen(command, cwd=directory, env=env, stdout=subprocess.PIPE, stderr=subprocess.PIPE, - start_new_session=os.name != "nt") - try: - stdout, stderr = process.communicate(timeout=seconds) - combined = (stdout + stderr).decode("utf-8", errors="replace") - return {"result": "pass" if process.returncode == 0 else "fail", "exitCode": process.returncode, - "bazel761": b"bazel 7.6.1" in stdout.lower(), - "httpStatuses": sorted({int(code) for code in re.findall(r"(?:HTTP(?:/[^ ]+)?(?: (?:response|status))?(?: code)?[: ]+|GET returned[: ]+|status code[: ]+)([45][0-9]{2})\b", combined, re.I)}), - "npmErrorCodes": sorted(set(re.findall(r"npm (?:error|ERR!) code (E[A-Z0-9_]{1,30})\b", combined))), - "configurationErrorReported": bool(re.search(r"unknown startup option|unrecognized option|no match found for version|no such package", combined, re.I)), - "timeoutReported": bool(re.search(r"timed? ?out|timeout", combined, re.I)), - "checksumMismatchReported": bool(re.search(r"checksum.*mismatch|checksum.*does not match", combined, re.I)), - "seconds": round(time.monotonic() - start, 3)} - except subprocess.TimeoutExpired: - kill_tree(process) - process.stdout.close() - process.stderr.close() - return {"result": "fail", "error": "deadline", "seconds": round(time.monotonic() - start, 3)} - - -def bazel_command(directory: Path) -> list[str]: - npx = shutil.which("npx") - if not npx: - raise RuntimeError("Node.js npx is required") - prefix = [npx, "--yes", BAZELISK_PACKAGE] - if os.name == "nt": - prefix = ["cmd.exe", "/d", "/c", *prefix] - return [*prefix, "--batch", "--ignore_all_rc_files", f"--output_user_root={directory / 'output'}"] - - -def repository_inventory(directory: Path) -> dict: - files = list((directory / "repository-cache" / "content_addressable" / "sha256").glob("*/file")) - valid = len(files) == 1 and files[0].stat().st_size <= SMALL_ARCHIVE_BYTES - if valid: - valid = hashlib.sha256(files[0].read_bytes()).hexdigest() == RULES_SHA256 - return {"result": "pass" if valid else "fail", "cachedArchiveCount": len(files), - "onlyPinnedSmallArchive": valid} - - -def bazel_probes(directory: Path) -> dict: - env = {key: value for key, value in os.environ.items() - if not key.upper().startswith(("BAZEL", "USE_BAZEL", "NPM_CONFIG", "NODE_OPTIONS")) - and not any(word in key.upper() for word in ("TOKEN", "SECRET", "PASSWORD", "CREDENTIAL"))} - env.update(USE_BAZEL_VERSION=BAZEL_VERSION, BAZELISK_HOME=str(directory / "bazelisk"), - BAZELISK_SKIP_WRAPPER="true", npm_config_cache=str(directory / "npm"), - npm_config_userconfig=str(directory / "empty-user.npmrc"), - npm_config_globalconfig=str(directory / "empty-global.npmrc"), - npm_config_registry="https://registry.npmjs.org") - (directory / "empty-user.npmrc").write_text("") - (directory / "empty-global.npmrc").write_text("") - (directory / "WORKSPACE").write_text( - 'workspace(name = "download_diagnostic")\n' - 'load("@bazel_tools//tools/build_defs/repo:http.bzl", "http_archive")\n' - f'http_archive(name="probe", url="{RULES_URL}", sha256="{RULES_SHA256}", ' - 'strip_prefix="rules_shell-0.4.1", build_file_content="filegroup(name=\\\"downloaded\\\", srcs=[])\\n")\n') - (directory / "BUILD").write_text("") - base = bazel_command(directory) - bootstrap = command([*base, "version", "--gnu_format"], directory, env, 75) - if bootstrap["result"] != "pass" or not bootstrap.get("bazel761"): - return {"bootstrap": bootstrap, "repository": {"result": "skipped"}} - repository = command([*base, "query", "--enable_bzlmod=false", f"--repository_cache={directory / 'repository-cache'}", "@probe//:downloaded"], directory, env, 60) - inventory = repository_inventory(directory) - if inventory["result"] != "pass": - repository["result"] = "fail" - return {"bootstrap": bootstrap, "repository": repository, "repositoryInventory": inventory, "bazeliskPackage": BAZELISK_PACKAGE, - "bazelVersion": BAZEL_VERSION, "repositorySha256": RULES_SHA256, - "scope": "actual bootstrap and checksum-enforced http_archive query; no build"} - - -def host_bazel_url() -> str: - key = (platform.system(), platform.machine().lower()) - names = {("Windows", "amd64"): "windows-x86_64.exe", ("Linux", "x86_64"): "linux-x86_64", - ("Linux", "aarch64"): "linux-arm64", ("Darwin", "arm64"): "darwin-arm64"} - if key not in names: - raise ValueError("Unsupported diagnostic runner") - return f"https://github.com/bazelbuild/bazel/releases/download/{BAZEL_VERSION}/bazel-{BAZEL_VERSION}-{names[key]}" - - -def write_report(path: Path, report: dict) -> None: - report["investigatedRelease"] = INVESTIGATION - report["diagnosticRun"] = { - key: os.environ[name] for key, name, pattern in ( - ("headSha", "GITHUB_SHA", r"[0-9a-f]{40}"), - ("runId", "GITHUB_RUN_ID", r"[0-9]{1,20}"), - ("runAttempt", "GITHUB_RUN_ATTEMPT", r"[0-9]{1,6}"), - ) if re.fullmatch(pattern, os.environ.get(name, "")) - } - path.write_text(json.dumps(report, indent=2) + "\n") - - -def run_round(report_path: Path) -> None: - with tempfile.TemporaryDirectory(prefix="litert-download-round-") as temporary: - directory = Path(temporary) - report = {"startedAtUtc": datetime.now(timezone.utc).isoformat(), "upstreamCommit": UPSTREAM, "platform": platform.system(), "arch": platform.machine(), "screens": {}} - write_report(report_path, report) - owner_path = directory / "owner.json" - owner_path.unlink(missing_ok=True) - owner_status = command([sys.executable, str(Path(__file__).resolve()), "--owner-report", str(owner_path)], ROOT, dict(os.environ), 45) - if owner_status["result"] != "pass": - report["ownerSmallArchive"] = owner_status - else: - try: - owner = json.loads(owner_path.read_text()) - if not isinstance(owner, dict) or owner.get("result") not in {"pass", "fail"}: - raise ValueError("Invalid owner report") - if owner["result"] == "pass" and ( - owner.get("sha256") != RULES_SHA256 - or type(owner.get("bytesRead")) is not int - or not 0 < owner["bytesRead"] <= SMALL_ARCHIVE_BYTES - ): - raise ValueError("Incomplete owner evidence") - report["ownerSmallArchive"] = owner - except (OSError, ValueError): - report["ownerSmallArchive"] = {"result": "fail", "error": "missing_or_invalid_owner_report"} - write_report(report_path, report) - report["actualBazel"] = bazel_probes(directory) - write_report(report_path, report) - samples = {**URLS, "bazel_binary": host_bazel_url()} - with ThreadPoolExecutor(max_workers=4) as pool: - for name, result in zip(samples, pool.map(screen, samples.values())): - report["screens"][name] = result - write_report(report_path, report) - - -def round_passed(report: dict) -> bool: - screens = report.get("screens", {}) - bazel = report.get("actualBazel", {}) - return ( - set(screens) == {*URLS, "bazel_binary"} - and all(item.get("result") == "pass" for item in screens.values()) - and report.get("ownerSmallArchive", {}).get("result") == "pass" - and bazel.get("bootstrap", {}).get("result") == "pass" - and bazel.get("bootstrap", {}).get("bazel761") is True - and bazel.get("repository", {}).get("result") == "pass" - and bazel.get("repositoryInventory", {}).get("onlyPinnedSmallArchive") is True - ) - - -def main() -> int: - parser = argparse.ArgumentParser(description=__doc__) - mode = parser.add_mutually_exclusive_group() - mode.add_argument("--round-report", type=Path) - mode.add_argument("--owner-report", type=Path) - args = parser.parse_args() - if args.owner_report: - write_report(args.owner_report, owner_download(args.owner_report.parent)) - return 0 - if args.round_report: - run_round(args.round_report) - return 0 - output = ROOT / "diagnostic-results" - output.mkdir(exist_ok=True) - start = time.monotonic() - summary = {"rounds": [], "intervalSeconds": INTERVAL_SECONDS, "roundDeadlineSeconds": ROUND_SECONDS, - "scope": "runner acquisition screening; not publication approval or release qualification"} - for index in range(ROUNDS): - time.sleep(max(0, start + index * INTERVAL_SECONDS - time.monotonic())) - path = output / f"round-{index + 1}.json" - path.unlink(missing_ok=True) - result = command([sys.executable, str(Path(__file__).resolve()), "--round-report", str(path)], ROOT, dict(os.environ), ROUND_SECONDS) - complete = result["result"] == "pass" and path.exists() and round_passed(json.loads(path.read_text())) - summary["rounds"].append({"round": index + 1, **result, "allAcquisitionsPassed": complete}) - write_report(output / "summary.json", summary) - print("Diagnostic sampling finished; inspect sanitized reports. No recovery or release claim.") - return 0 if all(item["allAcquisitionsPassed"] for item in summary["rounds"]) else 1 - - -if __name__ == "__main__": - # No traceback: arbitrary exception strings can contain redirect credentials. - try: - raise SystemExit(main()) - except Exception: - print("Diagnostic failed; raw exception suppressed.", file=sys.stderr) - raise SystemExit(1) diff --git a/diagnostics/test_runner_downloads.py b/diagnostics/test_runner_downloads.py deleted file mode 100644 index 2128bbf..0000000 --- a/diagnostics/test_runner_downloads.py +++ /dev/null @@ -1,234 +0,0 @@ -from __future__ import annotations - -import hashlib -import io -import json -from pathlib import Path -import re -import subprocess -import tempfile -import unittest -from unittest.mock import Mock, patch -import urllib.error - -import runner_downloads as diagnostic - - -class DownloadDiagnosticTest(unittest.TestCase): - def test_urls_and_clients_match_failed_transaction(self): - self.assertEqual(diagnostic.UPSTREAM, "e9fd8c53ff968071774206163027dd84bedfe925") - self.assertEqual(diagnostic.URLS["owner_source"], f"https://github.com/google-ai-edge/LiteRT-LM/archive/{diagnostic.UPSTREAM}.tar.gz") - self.assertEqual(diagnostic.USER_AGENT, "litert-lm-native-build") - self.assertEqual(diagnostic.BAZELISK_PACKAGE, "@bazel/bazelisk@1.28.1") - self.assertEqual(diagnostic.BAZEL_VERSION, "7.6.1") - self.assertEqual(diagnostic.RULES_SHA256, "bc61ef94facc78e20a645726f64756e5e285a045037c7a61f65af2941f4c25e1") - for system, machine, suffix in [("Windows", "AMD64", "windows-x86_64.exe"), ("Linux", "x86_64", "linux-x86_64"), ("Linux", "aarch64", "linux-arm64"), ("Darwin", "arm64", "darwin-arm64")]: - with self.subTest(system=system, machine=machine), patch.object(diagnostic.platform, "system", return_value=system), patch.object(diagnostic.platform, "machine", return_value=machine): - self.assertEqual(diagnostic.host_bazel_url(), f"https://github.com/bazelbuild/bazel/releases/download/7.6.1/bazel-7.6.1-{suffix}") - - def test_redirect_and_error_metadata_never_expose_queries_or_headers(self): - url = "https://user:password@release-assets.githubusercontent.com/path?signature=secret#token" - self.assertEqual(diagnostic.safe_url(url), "https://release-assets.githubusercontent.com/path") - self.assertEqual(diagnostic.safe_url("https://untrusted.invalid/secret?token=secret"), "[other-host]") - records = [] - handler = diagnostic.Redirects(records) - request = diagnostic.urllib.request.Request(diagnostic.RULES_URL) - handler.redirect_request(request, None, 302, "Found", {}, url) - self.assertNotIn("secret", json.dumps(records)) - error = urllib.error.HTTPError(url, 504, "private secret", {"Set-Cookie": "secret", "Location": url, "Retry-After": "2", "X-Cache": "HIT"}, None) - with patch.object(diagnostic.urllib.request, "build_opener") as opener: - opener.return_value.open.side_effect = error - result = diagnostic.screen(diagnostic.RULES_URL) - self.assertEqual(result["result"], "fail") - self.assertEqual(result["status"], 504) - self.assertEqual(result["retryAfterSeconds"], 2) - self.assertNotIn("secret", json.dumps(result)) - self.assertNotIn("password", json.dumps(result)) - error.close() - - def test_get_is_bounded_and_wrong_body_fails(self): - for body, expected in [(b"\x1f\x8btest", "pass"), (b"gateway error", "fail")]: - response = Mock(code=200, url=diagnostic.RULES_URL, headers={}) - response.read.return_value = body - opener = Mock() - opener.open.return_value.__enter__ = Mock(return_value=response) - opener.open.return_value.__exit__ = Mock(return_value=False) - with patch.object(diagnostic.urllib.request, "build_opener", return_value=opener): - result = diagnostic.screen(diagnostic.RULES_URL) - self.assertEqual(result["result"], expected) - response.read.assert_called_once_with(65536) - request = opener.open.call_args.args[0] - self.assertEqual(request.get_method(), "GET") - self.assertEqual(request.get_header("User-agent"), diagnostic.USER_AGENT) - - def test_complete_download_uses_production_client_and_rejects_wrong_checksum(self): - # Exercise the actual downloader over an in-memory transport, not network. - data = b"small archive fixture" - with tempfile.TemporaryDirectory() as temporary: - root = Path(temporary) - opener = Mock() - def response(*args, **kwargs): - body = io.BytesIO(data) - body.code, body.url, body.headers = 200, diagnostic.RULES_URL, {} - return body - opener.open.side_effect = response - with patch.object(diagnostic.urllib.request, "build_opener", return_value=opener), patch.object(diagnostic, "RULES_SHA256", hashlib.sha256(data).hexdigest()): - self.assertEqual(diagnostic.owner_download(root)["result"], "pass") - request = opener.open.call_args.args[0] - self.assertEqual(request.full_url, diagnostic.RULES_URL) - self.assertEqual(request.get_header("User-agent"), diagnostic.USER_AGENT) - self.assertEqual(opener.open.call_args.kwargs["timeout"], 60) - with patch.object(diagnostic.urllib.request, "build_opener", return_value=opener): - self.assertEqual(diagnostic.owner_download(root)["result"], "fail") - with self.assertRaisesRegex(ValueError, "checksum"): - diagnostic.verify_checksum(root / "rules_shell.tar.gz") - - def test_small_download_byte_limit_fails_closed(self): - response = diagnostic.LimitedResponse(io.BytesIO(b"x" * (diagnostic.SMALL_ARCHIVE_BYTES + 1))) - response.read(diagnostic.SMALL_ARCHIVE_BYTES) - with self.assertRaisesRegex(ValueError, "byte bound"): - response.read(1) - - def test_bazel_fetch_is_pinned_fresh_batch_and_has_no_build(self): - with tempfile.TemporaryDirectory() as temporary: - root = Path(temporary) - with patch.object(diagnostic.shutil, "which", return_value="npx"), patch.object(diagnostic, "command", side_effect=[{"result": "pass", "bazel761": True}, {"result": "pass"}]) as run, patch.object(diagnostic, "repository_inventory", return_value={"result": "pass", "onlyPinnedSmallArchive": True}): - result = diagnostic.bazel_probes(root) - self.assertEqual(result["repository"]["result"], "pass") - commands = [call.args[0] for call in run.call_args_list] - for command in commands: - self.assertIn("--batch", command) - self.assertIn("--ignore_all_rc_files", command) - self.assertIn(diagnostic.BAZELISK_PACKAGE, command) - self.assertIn(f"--output_user_root={root / 'output'}", command) - self.assertNotIn("build", command) - self.assertNotIn("run", command) - self.assertIn("query", commands[1]) - self.assertIn("@probe//:downloaded", commands[1]) - self.assertIn(f"--repository_cache={root / 'repository-cache'}", commands[1]) - env = run.call_args.args[2] - self.assertEqual(env["USE_BAZEL_VERSION"], "7.6.1") - self.assertEqual(env["BAZELISK_HOME"], str(root / "bazelisk")) - self.assertEqual(env["npm_config_cache"], str(root / "npm")) - workspace = (root / "WORKSPACE").read_text() - self.assertIn(f'sha256="{diagnostic.RULES_SHA256}"', workspace) - self.assertIn(f'url="{diagnostic.RULES_URL}"', workspace) - self.assertEqual(workspace.count("http_archive(name="), 1) - - def test_repository_inventory_rejects_wrong_hash_and_fetch_fanout(self): - with tempfile.TemporaryDirectory() as temporary: - root = Path(temporary) - path = root / "repository-cache/content_addressable/sha256/fixture/file" - path.parent.mkdir(parents=True) - path.write_bytes(b"fixture") - self.assertEqual(diagnostic.repository_inventory(root)["result"], "fail") - with patch.object(diagnostic, "RULES_SHA256", hashlib.sha256(b"fixture").hexdigest()): - self.assertEqual(diagnostic.repository_inventory(root)["result"], "pass") - extra = path.parents[1] / "extra/file" - extra.parent.mkdir() - extra.write_bytes(b"extra archive") - self.assertEqual(diagnostic.repository_inventory(root)["result"], "fail") - - def test_wrong_bazel_version_cannot_pass_or_fetch(self): - with tempfile.TemporaryDirectory() as temporary, patch.object(diagnostic.shutil, "which", return_value="npx"), patch.object(diagnostic, "command", return_value={"result": "pass", "bazel761": False}) as run: - result = diagnostic.bazel_probes(Path(temporary)) - self.assertEqual(result["repository"]["result"], "skipped") - self.assertEqual(run.call_count, 1) - self.assertFalse(diagnostic.round_passed({})) - - def test_deadlines_kill_client_and_suppress_raw_errors(self): - process = Mock() - process.communicate.side_effect = subprocess.TimeoutExpired("secret signed URL", 1, output=b"token=secret") - with patch.object(diagnostic.subprocess, "Popen", return_value=process), patch.object(diagnostic, "kill_tree") as kill: - result = diagnostic.command(["client"], Path("."), {}, 1) - kill.assert_called_once_with(process) - self.assertEqual(result["error"], "deadline") - self.assertNotIn("secret", json.dumps(result)) - self.assertEqual((diagnostic.ROUNDS, diagnostic.INTERVAL_SECONDS, diagnostic.ROUND_SECONDS), (3, 300, 240)) - - def test_production_round_rejects_failed_owner_even_with_passing_report(self): - passing_owner = {"result": "pass", "sha256": diagnostic.RULES_SHA256, "bytesRead": 22017} - passing_bazel = {"bootstrap": {"result": "pass", "bazel761": True}, - "repository": {"result": "pass"}, "repositoryInventory": {"onlyPinnedSmallArchive": True}} - cases = [ - ({"result": "fail", "error": "deadline"}, passing_owner, False), - ({"result": "fail", "exitCode": 1}, passing_owner, False), - ({"result": "pass"}, None, False), - ({"result": "pass"}, {"result": "pass"}, False), - ({"result": "pass"}, passing_owner, True), - ] - for status, payload, expected in cases: - with self.subTest(status=status, payload=payload), tempfile.TemporaryDirectory() as temporary: - output = Path(temporary) / "round.json" - def owner_worker(command, *args): - path = Path(command[-1]) - self.assertFalse(path.exists(), "Owner evidence must be fresh") - if payload is not None: - path.write_text(json.dumps(payload)) - return status - with patch.object(diagnostic, "command", side_effect=owner_worker), patch.object(diagnostic, "bazel_probes", return_value=passing_bazel), patch.object(diagnostic, "screen", return_value={"result": "pass"}), patch.object(diagnostic, "host_bazel_url", return_value="https://example.invalid/bazel"): - diagnostic.run_round(output) - report = json.loads(output.read_text()) - self.assertEqual(diagnostic.round_passed(report), expected) - if status["result"] == "fail": - self.assertEqual(report["ownerSmallArchive"], status) - - def test_worker_failure_and_stale_pass_report_cannot_pass(self): - for worker_result in ("pass", "fail"): - with self.subTest(worker_result=worker_result), tempfile.TemporaryDirectory() as temporary: - root = Path(temporary) - output = root / "diagnostic-results" - output.mkdir() - stale = output / "round-1.json" - stale.write_text('{"oldPassedEvidence": true}') - def worker(*args): - self.assertFalse(stale.exists(), "Old report must be removed before launch") - if worker_result == "fail": - stale.write_text('{"newButIncomplete": true}') - return {"result": worker_result} - with patch.object(diagnostic, "ROOT", root), patch.object(diagnostic, "ROUNDS", 1), patch.object(diagnostic, "command", side_effect=worker), patch.object(diagnostic, "round_passed", return_value=True), patch.object(diagnostic.time, "sleep"), patch.object(diagnostic.sys, "argv", ["diagnostic"]): - self.assertEqual(diagnostic.main(), 1) - self.assertFalse(json.loads((output / "summary.json").read_text())["rounds"][0]["allAcquisitionsPassed"]) - - def test_sanitized_client_errors_and_diagnostic_identity(self): - process = Mock(returncode=1) - process.communicate.return_value = (b"", b"HTTP 504 https://host/path?token=secret npm error code E404 checksum mismatch timeout") - with patch.object(diagnostic.subprocess, "Popen", return_value=process): - result = diagnostic.command(["client"], Path("."), {}, 1) - self.assertEqual(result["httpStatuses"], [504]) - self.assertEqual(result["npmErrorCodes"], ["E404"]) - self.assertTrue(result["checksumMismatchReported"]) - self.assertTrue(result["timeoutReported"]) - self.assertNotIn("secret", json.dumps(result)) - with tempfile.TemporaryDirectory() as temporary, patch.dict(diagnostic.os.environ, {"GITHUB_SHA": "a" * 40, "GITHUB_RUN_ID": "123", "GITHUB_RUN_ATTEMPT": "2", "GITHUB_TOKEN": "secret"}): - path = Path(temporary) / "report.json" - diagnostic.write_report(path, {}) - report = json.loads(path.read_text()) - self.assertEqual(report["diagnosticRun"], {"headSha": "a" * 40, "runId": "123", "runAttempt": "2"}) - self.assertEqual(report["investigatedRelease"]["nativeCommit"], "deef59818b0514c54929d7215c10ed6cba3b0f63") - self.assertNotIn("secret", path.read_text()) - - def test_workflow_is_manual_read_only_and_has_only_diagnostic_command(self): - source = (diagnostic.ROOT / ".github/workflows/runner_download_diagnostic.yml").read_text() - self.assertEqual(source.split("on:\n", 1)[1].split("\npermissions:", 1)[0].strip(), "workflow_dispatch:") - self.assertEqual(re.findall(r"^permissions:\n((?: .+\n)+)", source, re.M), [" contents: read\n"]) - self.assertNotRegex(source, r"(?m)^[ \t]+(permissions|environment|secrets):") - self.assertEqual(re.findall(r"(?m)^\s+run: (.+)$", source), ["python diagnostics/runner_downloads.py"]) - self.assertNotRegex(source, r"(?m)^\s+run: [|>]") - self.assertEqual(re.findall(r"(?m)^[ \t]+(?:- )?uses: (.+)$", source), ["actions/checkout@v6", "actions/setup-node@v4", "actions/upload-artifact@v4"]) - self.assertIn("uses: actions/upload-artifact@v4", source) - self.assertIn("persist-credentials: false", source) - self.assertIn("timeout-minutes: 17", source) - self.assertIn("os: [windows-latest, ubuntu-latest, ubuntu-24.04-arm, macos-latest]", source) - self.assertIn("path: diagnostic-results/*.json", source) - self.assertNotIn("secrets.", source) - self.assertNotIn("github.token", source) - self.assertNotRegex(source, r"(?m)^[ \t]+env:") - self.assertNotRegex(source, r"run: [^\n]+\n[ \t]{9,}[^ \t\n]") - qualification = (diagnostic.ROOT / ".github/workflows/pr_release_qualification.yml").read_text().split("concurrency:", 1)[0] - self.assertNotIn("diagnostics/", qualification) - self.assertNotIn("runner_download_diagnostic.yml", qualification) - - -if __name__ == "__main__": - unittest.main() diff --git a/docs/release_protocol.md b/docs/release_protocol.md index 47a5801..30c6672 100644 --- a/docs/release_protocol.md +++ b/docs/release_protocol.md @@ -61,7 +61,7 @@ and immediate lower same-line predecessor, reuse or decrease of a rebuild number legacy output forms, partial publication matrices, and publication without the required real-model smoke evidence. -Stable manual preflight applies the same consumability decision as scheduled +Stable manual preflight applies the same consumability decision as upstream detection before any of the eight platform builds start. A metadata-only tag at an already packaged commit is rejected unless the requested native identity is an explicitly ordered rebuild, and every stable input must publish the required @@ -116,7 +116,7 @@ on Linux x64, Windows x64, and macOS arm64. It contains no publication input, write permission, release command, or call into the write-scoped publication job. -The scheduled `.github/workflows/auto_upstream_release.yml` only detects a +The manually dispatched `.github/workflows/auto_upstream_release.yml` only detects a consumable stable upstream candidate and uploads `preparation.json`. It has read-only permissions and cannot dispatch the build or publish. diff --git a/tools/qualification_scope.py b/tools/qualification_scope.py index 7d7d065..6082f22 100644 --- a/tools/qualification_scope.py +++ b/tools/qualification_scope.py @@ -6,7 +6,7 @@ import subprocess MATRIX = [{'os': 'ubuntu-24.04', 'platform': 'linux', 'arch': 'x64', 'jobs': '3', 'bazel_output_root': '.bazel-output-root', 'timeout_minutes': 90}, {'os': 'ubuntu-24.04-arm', 'platform': 'linux', 'arch': 'arm64', 'jobs': '3', 'bazel_output_root': '.bazel-output-root', 'timeout_minutes': 90}, {'os': 'windows-latest', 'platform': 'windows', 'arch': 'x64', 'jobs': '3', 'bazel_output_root': 'C:/bzl', 'timeout_minutes': 120}, {'os': 'ubuntu-latest', 'platform': 'android', 'arch': 'arm64', 'jobs': '3', 'bazel_output_root': '.bazel-output-root', 'timeout_minutes': 90}, {'os': 'ubuntu-latest', 'platform': 'android', 'arch': 'x64', 'jobs': '3', 'bazel_output_root': '.bazel-output-root', 'timeout_minutes': 90}, {'os': 'macos-latest', 'platform': 'ios', 'arch': 'arm64', 'jobs': '3', 'bazel_output_root': '.bazel-output-root', 'timeout_minutes': 120}, {'os': 'macos-latest', 'platform': 'ios', 'arch': 'arm64-sim', 'jobs': '3', 'bazel_output_root': '.bazel-output-root', 'timeout_minutes': 120}, {'os': 'macos-latest', 'platform': 'macos', 'arch': 'arm64', 'jobs': '3', 'bazel_output_root': '.bazel-output-root', 'timeout_minutes': 120}] -TOOLING = frozenset(['diagnostics/repair_qwen3_tokenizer.py', 'diagnostics/runner_downloads.py', 'diagnostics/test_repair_qwen3_tokenizer.py', 'diagnostics/test_runner_downloads.py', 'tests/test_release_tag_lifecycle.py', 'tools/test_build_upstream_runtime.py', 'tools/test_check_upstream_release.py', 'tools/test_download_utils.py', 'tools/test_fetch_litert_lm_asr_smoke_assets.py', 'tools/test_git_lfs_utils.py', 'tools/test_linux_runtime_metadata.py', 'tools/test_litert_lm_asr_smoke.py', 'tools/test_litert_lm_bridge.py', 'tools/test_litert_lm_finish_reason_smoke.py', 'tools/test_litert_lm_symbols.py', 'tools/test_macos_runtime_identity.py', 'tools/test_macos_runtime_policy.py', 'tools/test_macos_spm_layout.py', 'tools/test_package_ios_runtime.py', 'tools/test_package_macos_runtime.py', 'tools/test_package_release.py', 'tools/test_package_upstream_prebuilts.py', 'tools/test_prebuilt_overrides.py', 'tools/test_publication_state.py', 'tools/test_qualification_scheduling.py', 'tools/test_release_readback.py', 'tools/test_release_result.py', 'tools/test_release_version_policy.py', 'tools/test_runtime_dependency_utils.py', 'tools/test_stream_finish_reason_patch.py', 'tools/test_upstream_archive.py', 'tools/test_validate_publication_intent.py', 'tools/test_validate_release_manifest.py', 'tools/test_verify_qualification_source.py', 'tools/test_windows_dxc.py', 'tools/test_windows_runtime.py', 'tools/test_xnnpack_pf32_sme2_patch.py', 'tools/test_xnnpack_pqs8_qc4w_sme2_patch.py']) +TOOLING = frozenset(['diagnostics/repair_qwen3_tokenizer.py', 'diagnostics/test_repair_qwen3_tokenizer.py', 'tests/test_release_tag_lifecycle.py', 'tools/test_build_upstream_runtime.py', 'tools/test_check_upstream_release.py', 'tools/test_download_utils.py', 'tools/test_fetch_litert_lm_asr_smoke_assets.py', 'tools/test_git_lfs_utils.py', 'tools/test_linux_runtime_metadata.py', 'tools/test_litert_lm_asr_smoke.py', 'tools/test_litert_lm_bridge.py', 'tools/test_litert_lm_finish_reason_smoke.py', 'tools/test_litert_lm_symbols.py', 'tools/test_macos_runtime_identity.py', 'tools/test_macos_runtime_policy.py', 'tools/test_macos_spm_layout.py', 'tools/test_package_ios_runtime.py', 'tools/test_package_macos_runtime.py', 'tools/test_package_release.py', 'tools/test_package_upstream_prebuilts.py', 'tools/test_prebuilt_overrides.py', 'tools/test_publication_state.py', 'tools/test_qualification_scheduling.py', 'tools/test_release_readback.py', 'tools/test_release_result.py', 'tools/test_release_version_policy.py', 'tools/test_runtime_dependency_utils.py', 'tools/test_stream_finish_reason_patch.py', 'tools/test_upstream_archive.py', 'tools/test_validate_publication_intent.py', 'tools/test_validate_release_manifest.py', 'tools/test_verify_qualification_source.py', 'tools/test_windows_dxc.py', 'tools/test_windows_runtime.py', 'tools/test_xnnpack_pf32_sme2_patch.py', 'tools/test_xnnpack_pqs8_qc4w_sme2_patch.py']) PLATFORM_TOOLS = { 'tools/package_macos_runtime.py': 'macos', 'tools/macos_runtime_identity.py': 'macos', diff --git a/tools/test_release_version_policy.py b/tools/test_release_version_policy.py index 26b085e..04a7d36 100644 --- a/tools/test_release_version_policy.py +++ b/tools/test_release_version_policy.py @@ -47,11 +47,13 @@ def test_existing_tags_file_read_errors_are_clean(self) -> None: ): release_policy_main() - def test_scheduled_workflow_is_detection_only(self) -> None: + def test_detection_workflow_is_manual_and_detection_only(self) -> None: root = Path(__file__).resolve().parents[1] workflow = (root / ".github/workflows/auto_upstream_release.yml").read_text( encoding="utf-8" ) + self.assertIn("workflow_dispatch:", workflow) + self.assertNotIn("schedule:", workflow) self.assertIn("contents: read", workflow) self.assertIn("persist-credentials: false", workflow) self.assertIn("preparation.json", workflow)