diff --git a/.github/workflows/r2-upload-tests.yml b/.github/workflows/r2-upload-tests.yml index 8a054892b6fc..bdf5df9ddac5 100644 --- a/.github/workflows/r2-upload-tests.yml +++ b/.github/workflows/r2-upload-tests.yml @@ -16,6 +16,9 @@ on: - .github/workflows/cmux-tui-artifacts-retry.yml - scripts/ci/cmux_tui_artifacts_retry.py - tests/test_cmux_tui_artifacts_retry.py + - .github/workflows/stable-feed-watch.yml + - scripts/ci/verify_stable_feed.py + - tests/test_verify_stable_feed.py workflow_dispatch: permissions: @@ -36,3 +39,4 @@ jobs: # finalize-release.py runs only at real publish time; at least prove it loads. - run: python3 scripts/ci/finalize-release.py publish --help && python3 scripts/ci/finalize-release.py download --help && python3 scripts/ci/finalize-release.py adopt --help - run: python3 tests/test_cmux_tui_artifacts_retry.py + - run: python3 tests/test_verify_stable_feed.py diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 59d547814e2d..f27803c3a7e9 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -1059,3 +1059,40 @@ jobs: ./scripts/ci/signing-keychain.sh delete --keychain build.keychain \ || security delete-keychain build.keychain >/dev/null 2>&1 || true rm -f /tmp/cert.p12 + + # Fetch every stable feed the way Sparkle does, plus this release's own, and + # every DMG they list. v0.65.2.2 went out green with 0 assets on the + # published release, so every update check failed + # (https://github.com/manaflow-ai/cmux/issues/26729). Its own job: the + # Homebrew cask gates on build-sign-notarize alone, so a red check here stays + # visible without holding the cask. stable-feed-watch.yml checks the default + # feeds hourly from main regardless of which branch published them; it does + # not check non-latest backports' own tag feeds. Those are covered only by + # each tag's release workflow when it includes this job. + verify-stable-feed: + needs: build-sign-notarize + if: github.event_name == 'push' && startsWith(github.ref, 'refs/tags/') + permissions: + contents: read + runs-on: ${{ github.repository_owner != 'manaflow-ai' && 'ubuntu-24.04' || fromJSON(vars.RUNNER_POOLS).linux_2 || 'blacksmith-2vcpu-ubuntu-2404' }} + timeout-minutes: 20 + steps: + - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 + with: + persist-credentials: false + # A backport tag (for example v0.62.1 after v0.63.1) never becomes latest, + # so it answers only for its own feeds. + - name: Verify stable feeds deliver an update + env: + GH_TOKEN: ${{ github.token }} + run: | + set -euo pipefail + latest="$(gh release list --repo "$GITHUB_REPOSITORY" --exclude-drafts --exclude-pre-releases \ + --json tagName -q '.[].tagName' | sort -V | tail -1)" + scope=() + if [ "$latest" != "$GITHUB_REF_NAME" ]; then + echo "$GITHUB_REF_NAME is not the latest stable release ($latest); checking only its own feeds" + scope=(--tag-only) + fi + python3 scripts/ci/verify_stable_feed.py --repo "$GITHUB_REPOSITORY" --tag "$GITHUB_REF_NAME" \ + --settle-seconds 600 "${scope[@]+"${scope[@]}"}" diff --git a/.github/workflows/stable-feed-watch.yml b/.github/workflows/stable-feed-watch.yml new file mode 100644 index 000000000000..20ba9e9ed77e --- /dev/null +++ b/.github/workflows/stable-feed-watch.yml @@ -0,0 +1,39 @@ +name: Stable feed watch + +# Every stable install checks releases/latest/download/appcast.xml (or its +# per-architecture rewrite). On 2026-10-27 v0.65.2.2 was tagged from a hotfix +# branch whose release.yml still published by tag: the published release had 0 +# assets, every feed URL 404ed, and every 0.65.2 install showed "error +# retrieving update information" behind a green release run +# (https://github.com/manaflow-ai/cmux/issues/26729). A tag runs the workflow +# file at that tag, so an older branch may omit release.yml's feed check. This +# schedule runs from main and checks the default stable feeds regardless of +# which branch published them. A non-latest backport's own tag feeds are checked +# only by its release workflow when it includes the check. The script probes +# every listed enclosure (scripts/ci/verify_stable_feed.py, tested by +# tests/test_verify_stable_feed.py) and goes red on any problem. +on: + schedule: + - cron: "23 * * * *" + workflow_dispatch: + +permissions: {} + +concurrency: + group: stable-feed-watch + cancel-in-progress: false + +jobs: + watch: + if: github.repository_owner == 'manaflow-ai' + runs-on: ${{ github.repository_owner != 'manaflow-ai' && 'ubuntu-24.04' || fromJSON(vars.RUNNER_POOLS).linux_2 || 'blacksmith-2vcpu-ubuntu-2404' }} + timeout-minutes: 15 + permissions: + contents: read + steps: + - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 + with: + persist-credentials: false + - name: Check every stable feed and its enclosures + # A feed uploaded minutes ago can still serve GitHub's cached 404. + run: python3 scripts/ci/verify_stable_feed.py --settle-seconds 180 diff --git a/scripts/ci/verify_stable_feed.py b/scripts/ci/verify_stable_feed.py new file mode 100755 index 000000000000..8ecf2dde2bb0 --- /dev/null +++ b/scripts/ci/verify_stable_feed.py @@ -0,0 +1,269 @@ +#!/usr/bin/env python3 +"""Fail when a stable Sparkle feed cannot deliver an update. + +Installed stable apps check releases/latest/download/appcast.xml (thin builds +rewrite it to appcast-.xml), and files.cmux.com/stable/ serves the same +feeds from R2. On 2026-10-27 v0.65.2.2 was tagged from a hotfix branch that +still carried the publish-by-tag release workflow: the published release had 0 +assets while all 12 sat on a hidden draft, so every latest/download feed URL +404ed and every 0.65.2 install showed "error retrieving update information" +(https://github.com/manaflow-ai/cmux/issues/26729). The release run was green. + +Each feed must load, parse, and list at least one enclosure carrying an EdDSA +signature. Every enclosure must return the requested byte. Its reported full +size must match the feed's declared length; when the response reports no full +size, the enclosure passes without a length comparison. This probe does not +verify complete DMG contents or cryptographically validate the signature. +release.yml runs it after publishing with --tag, which adds the new release's +own feed URLs. stable-feed-watch.yml checks the default feeds hourly from main, +regardless of which branch published the release. A non-latest backport's own +feeds are checked only by its release workflow when it includes this check. + +Right after an upload GitHub can serve a cached 404 for a few minutes, so +--settle-seconds retries failing feeds in rounds, 404 included, within one +shared window. The deadline limits retry starts; HTTP calls already running +can finish afterward, and the workflows enforce their own job timeouts. +Retry windows are cancellation-aware: SIGINT/SIGTERM stops further requests +and interrupts a pending backoff; an in-flight HTTP call retains its timeout. + +usage: verify_stable_feed.py [--feed URL ...] [--tag vX.Y.Z [--tag-only]] [--attempts 3] [--settle-seconds 0] +Exits 1 with one line per problem. +""" +from __future__ import annotations + +import argparse +import http.client +import re +import signal +import sys +import threading +import time +import urllib.error +import urllib.request +import xml.etree.ElementTree as ET + +SPARKLE_NS = "http://www.andymatuschak.org/xml-namespaces/sparkle" +DEFAULT_FEEDS = ( + "https://github.com/manaflow-ai/cmux/releases/latest/download/appcast.xml", + "https://github.com/manaflow-ai/cmux/releases/latest/download/appcast-arm64.xml", + "https://github.com/manaflow-ai/cmux/releases/latest/download/appcast-x86_64.xml", + "https://files.cmux.com/stable/appcast.xml", + "https://files.cmux.com/stable/appcast-arm64.xml", + "https://files.cmux.com/stable/appcast-x86_64.xml", +) +FEED_NAMES = ("appcast.xml", "appcast-arm64.xml", "appcast-x86_64.xml") +USER_AGENT = "cmux-stable-feed-check" + + +class FetchError(Exception): + pass + + +class RetryCancelled(Exception): + """The caller cancelled verification; no further request may start.""" + + +class RetryWindow: + """Bound retry starts by a monotonic deadline and an interruptible event. + + A successful HTTP response establishes readiness. Waiting only spaces + attempts; it never turns a failed response into a successful result. + In-flight HTTP requests retain their own 30-second timeout. + """ + + def __init__(self, seconds: float, *, cancelled: threading.Event | None = None): + """Capture one absolute deadline and share the caller's cancellation.""" + self.deadline = time.monotonic() + max(0, seconds) + self.cancelled = cancelled if cancelled is not None else threading.Event() + + def check_cancelled(self): + """Stop before another request or retry if cancellation was signalled.""" + if self.cancelled.is_set(): + raise RetryCancelled() + + def ready(self) -> bool: + """Whether a retry can start now, excluding the deadline itself.""" + self.check_cancelled() + return time.monotonic() < self.deadline + + def wait(self, seconds: float) -> bool: + """Wait for a retry slot, waking on cancellation or the deadline.""" + self.check_cancelled() + remaining = self.deadline - time.monotonic() + if remaining <= 0: + return False + if self.cancelled.wait(min(seconds, remaining)): + raise RetryCancelled() + return self.ready() + + +def http_get(url: str) -> bytes: + """Load a feed with a finite request timeout and uniform fetch errors.""" + request = urllib.request.Request(url, headers={"Cache-Control": "no-cache", "User-Agent": USER_AGENT}) + try: + with urllib.request.urlopen(request, timeout=30) as response: + return response.read() + except urllib.error.HTTPError as error: + raise FetchError(f"HTTP {error.code}") from error + except (urllib.error.URLError, OSError, http.client.HTTPException, ValueError) as error: + raise FetchError(str(getattr(error, "reason", error))) from error + + +def served_length(status: int, content_range: str | None, content_length: str | None) -> int | None: + """The full size from a one-byte range response, or None if unknown.""" + if status == 206 and content_range: + match = re.fullmatch(r"bytes \d+-\d+/(\d+)", content_range.strip()) + return int(match.group(1)) if match else None + return int(content_length) if content_length and content_length.isdigit() else None + + +def http_content_length(url: str) -> int | None: + """Asks for one byte and returns the full size the server reports. + + urllib turns a redirected HEAD into a GET, so a HEAD to GitHub's release + URL would start a full DMG download; a range request follows the redirect + and transfers one byte.""" + request = urllib.request.Request(url, headers={"Range": "bytes=0-0", "User-Agent": USER_AGENT}) + try: + with urllib.request.urlopen(request, timeout=30) as response: + if not response.read(1): + raise FetchError("response closed before the requested byte") + return served_length(response.status, response.headers.get("Content-Range"), + response.headers.get("Content-Length")) + except urllib.error.HTTPError as error: + raise FetchError(f"HTTP {error.code}") from error + except (urllib.error.URLError, OSError, http.client.HTTPException, ValueError) as error: + raise FetchError(str(getattr(error, "reason", error))) from error + + +def with_retries(attempts: int, call, *args, retry: RetryWindow | None = None, + cancelled: threading.Event | None = None): + """GitHub's release CDN returns a transient 5xx or reset now and then; a + 404 is the failure this check exists for, so it is never retried here. + The window bounds the attempt timeouts plus their backoff intervals.""" + retry = retry or RetryWindow(30 * attempts + attempts * (attempts - 1), cancelled=cancelled) + for attempt in range(1, attempts + 1): + retry.check_cancelled() + try: + result = call(*args) + retry.check_cancelled() + return result + except FetchError as error: + if attempt == attempts or str(error).startswith("HTTP 4"): + raise + if not retry.wait(2 * attempt): + raise + + +def enclosures(feed_xml: bytes) -> list[dict[str, str]]: + """Returns each item's enclosure attributes; raises ValueError on bad XML.""" + try: + root = ET.fromstring(feed_xml) + except ET.ParseError as error: + raise ValueError(f"does not parse as XML ({error})") from error + found = [] + for item in root.iter("item"): + enclosure = item.find("enclosure") + if enclosure is None: + continue + found.append({ + "url": enclosure.get("url", ""), + "length": enclosure.get("length", ""), + "signature": enclosure.get(f"{{{SPARKLE_NS}}}edSignature", ""), + }) + return found + + +def check_feed(feed_url: str, attempts: int, get=http_get, content_length=http_content_length, + *, cancelled: threading.Event | None = None) -> list[str]: + """Returns one line per problem with the feed or any enclosure it lists.""" + try: + body = with_retries(attempts, get, feed_url, cancelled=cancelled) + except FetchError as error: + return [f"{feed_url}: feed did not load ({error})"] + try: + items = enclosures(body) + except ValueError as error: + return [f"{feed_url}: feed {error}"] + if not items: + return [f"{feed_url}: feed lists no item with an enclosure"] + problems = [] + for item in items: + url = item["url"] + if not url: + problems.append(f"{feed_url}: an enclosure has no url") + continue + if not item["signature"]: + problems.append(f"{feed_url}: {url} has no sparkle:edSignature") + try: + if not (item["length"].isascii() and item["length"].isdigit()): + raise ValueError("length must contain ASCII digits") + declared_length = int(item["length"]) + except ValueError: + problems.append(f"{feed_url}: {url} has no numeric length") + continue + try: + served = with_retries(attempts, content_length, url, cancelled=cancelled) + except FetchError as error: + problems.append(f"{feed_url}: {url} does not download ({error})") + continue + if served is not None and served != declared_length: + problems.append(f"{feed_url}: {url} serves {served} bytes, the feed declares {item['length']}") + return problems + + +def main(argv: list[str] | None = None, *, cancelled: threading.Event | None = None) -> int: + """Check every selected feed, retry failures fairly, and report final results.""" + parser = argparse.ArgumentParser(description=__doc__.splitlines()[0]) + parser.add_argument("--feed", action="append", help="feed URL to check (repeatable; default: every stable feed)") + parser.add_argument("--tag", help="also check this release's own feeds (releases/download/TAG/...)") + parser.add_argument("--tag-only", action="store_true", help="check only the --tag feeds (a backport release)") + parser.add_argument("--repo", default="manaflow-ai/cmux") + parser.add_argument("--attempts", type=int, default=3) + parser.add_argument("--settle-seconds", type=int, default=0, + help="retry failing feeds in rounds within this shared window (404 included)") + args = parser.parse_args(argv) + if args.tag_only and not args.tag: + parser.error("--tag-only needs --tag") + feeds = [] if args.tag_only else list(args.feed or DEFAULT_FEEDS) + if args.tag: + feeds += [f"https://github.com/{args.repo}/releases/download/{args.tag}/{name}" for name in FEED_NAMES] + retries = RetryWindow(args.settle_seconds, cancelled=cancelled) + try: + results = [check_feed(feed_url, max(1, args.attempts), cancelled=retries.cancelled) for feed_url in feeds] + while any(results) and retries.wait(15): + for index, feed_url in enumerate(feeds): + if results[index] and retries.ready(): + print(f"wait {feed_url}: {results[index][0]}") + results[index] = check_feed(feed_url, max(1, args.attempts), cancelled=retries.cancelled) + except RetryCancelled: + print("Feed verification cancelled") + return 130 + problems = [] + for feed_url, found in zip(feeds, results): + print(f"{'FAIL' if found else 'ok '} {feed_url}") + problems.extend(found) + for problem in problems: + print(f"::error::{problem}") + return 1 if problems else 0 + + +def cli() -> int: + """Let SIGINT/SIGTERM cancel retry waits and restore the caller's handlers.""" + cancelled = threading.Event() + previous = {} + + def cancel(_signum, _frame): + cancelled.set() + + try: + for signum in (signal.SIGINT, signal.SIGTERM): + previous[signum] = signal.signal(signum, cancel) + return main(cancelled=cancelled) + finally: + for signum, handler in previous.items(): + signal.signal(signum, handler) + + +if __name__ == "__main__": + sys.exit(cli()) diff --git a/tests/test-execution.toml b/tests/test-execution.toml index 6f2c93fc5244..d3d9d6ed4f49 100644 --- a/tests/test-execution.toml +++ b/tests/test-execution.toml @@ -2211,6 +2211,10 @@ lane = "linux-guard" path = "tests/test_ci_fleet_rule_lints.py" lane = "linux-guard" +[[test]] +path = "tests/test_verify_stable_feed.py" +lane = "linux-guard" + [[test]] path = "tests/test_cloud_capture_provision.py" lane = "manual" diff --git a/tests/test_verify_stable_feed.py b/tests/test_verify_stable_feed.py new file mode 100644 index 000000000000..d8fa52aae849 --- /dev/null +++ b/tests/test_verify_stable_feed.py @@ -0,0 +1,385 @@ +#!/usr/bin/env python3 +"""Stable Sparkle feed check (scripts/ci/verify_stable_feed.py). + +v0.65.2.2 was published with 0 assets, so every releases/latest/download feed +URL 404ed and 0.65.2 installs showed "error retrieving update information" +(https://github.com/manaflow-ai/cmux/issues/26729). These cases pin what the +check refuses: a missing feed, a feed that does not parse, an unsigned or +empty feed, an enclosure that 404s, and one whose size disagrees. +""" +from __future__ import annotations + +import contextlib +import importlib.util +import io +from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer +from pathlib import Path +import signal +import subprocess +import sys +import threading +import unittest +from unittest.mock import patch + +SCRIPT = Path(__file__).resolve().parents[1] / "scripts/ci/verify_stable_feed.py" +spec = importlib.util.spec_from_file_location("verify_stable_feed", SCRIPT) +feed = importlib.util.module_from_spec(spec) +sys.modules["verify_stable_feed"] = feed +spec.loader.exec_module(feed) + +FEED_URL = "https://github.com/o/r/releases/latest/download/appcast.xml" +DMG = "https://github.com/o/r/releases/download/v1.2.3/cmux-macos.dmg" +EXPECTED_FEED_NAMES = ("appcast.xml", "appcast-arm64.xml", "appcast-x86_64.xml") + + +def appcast(*enclosures: str) -> bytes: + """Build an RSS feed containing exactly the supplied enclosures.""" + items = "".join(f"1.2.3{e}" for e in enclosures) + return ( + 'cmux{items}' + ).encode() + + +def enclosure(url=DMG, length="100", signature="c2ln") -> str: + """Build an enclosure, optionally omitting its signature.""" + sig = f' sparkle:edSignature="{signature}"' if signature else "" + return f'' + + +class Server: + """Answers GET and HEAD from a URL table; a missing URL is a 404.""" + + def __init__(self, bodies=None, lengths=None, failures=None): + """Set up response fixtures and a log independent of production code.""" + self.bodies = bodies or {} + self.lengths = lengths or {} + self.failures = dict(failures or {}) + self.calls = [] + + def _fail(self, url): + """Consume one queued failure before serving a fixture response.""" + queued = self.failures.get(url) + if queued: + raise feed.FetchError(queued.pop(0)) + + def get(self, url): + """Record the feed request and serve its body or a fetch failure.""" + self.calls.append(("GET", url)) + self._fail(url) + if url not in self.bodies: + raise feed.FetchError("HTTP 404") + return self.bodies[url] + + def head(self, url): + """Record an enclosure probe and serve its reported full size.""" + self.calls.append(("HEAD", url)) + self._fail(url) + if url not in self.lengths: + raise feed.FetchError("HTTP 404") + return self.lengths[url] + + +def quiet_main(argv): + """main() prints ::error:: lines; keep them out of the CI run's annotations.""" + with contextlib.redirect_stdout(io.StringIO()): + return feed.main(argv) + + +def quiet_main_with_cancellation(argv, cancelled): + """Capture cancellation diagnostics just like ordinary CLI diagnostics.""" + with contextlib.redirect_stdout(io.StringIO()): + return feed.main(argv, cancelled=cancelled) + + +def check(server, attempts=1): + return feed.check_feed(FEED_URL, attempts, get=server.get, content_length=server.head) + + +class Clock: + def __init__(self): + self.now = 0 + + def monotonic(self): + return self.now + + def sleep(self, seconds): + self.now += seconds + + +@contextlib.contextmanager +def range_server(body): + """Serve an actual one-byte range response and record the request header.""" + ranges = [] + + class Handler(BaseHTTPRequestHandler): + def do_GET(self): + """Advertise one byte even when the test deliberately omits it.""" + ranges.append(self.headers.get("Range")) + self.send_response(206) + self.send_header("Content-Range", "bytes 0-0/100") + self.send_header("Content-Length", "1") + self.end_headers() + self.wfile.write(body) + + def log_message(self, *_args): + pass + + with ThreadingHTTPServer(("127.0.0.1", 0), Handler) as server: + thread = threading.Thread(target=server.serve_forever, daemon=True) + thread.start() + try: + yield f"http://127.0.0.1:{server.server_port}/update.dmg", ranges + finally: + server.shutdown() + thread.join() + + +class VerifyStableFeedTests(unittest.TestCase): + def test_healthy_feed_passes(self): + server = Server({FEED_URL: appcast(enclosure())}, {DMG: 100}) + self.assertEqual(check(server), []) + + def test_published_release_without_assets_fails(self): + # The v0.65.2.2 state: latest/download/appcast.xml is a 404. + problems = check(Server()) + self.assertEqual(problems, [f"{FEED_URL}: feed did not load (HTTP 404)"]) + + def test_enclosure_that_404s_fails(self): + # The R2 feed pointed at DMGs on the empty release. + problems = check(Server({FEED_URL: appcast(enclosure())})) + self.assertEqual(problems, [f"{FEED_URL}: {DMG} does not download (HTTP 404)"]) + + def test_size_mismatch_fails(self): + problems = check(Server({FEED_URL: appcast(enclosure())}, {DMG: 99})) + self.assertIn("serves 99 bytes, the feed declares 100", problems[0]) + + def test_missing_content_length_is_not_a_mismatch(self): + server = Server({FEED_URL: appcast(enclosure())}, {DMG: None}) + self.assertEqual(check(server), []) + + def test_non_ascii_length_is_reported_without_a_traceback(self): + server = Server({FEED_URL: appcast(enclosure(length="²"))}, {DMG: 100}) + self.assertEqual(check(server), [f"{FEED_URL}: {DMG} has no numeric length"]) + + def test_range_response_that_closes_before_its_byte_fails(self): + with range_server(b"") as (url, _ranges): + with self.assertRaises(feed.FetchError): + feed.http_content_length(url) + + def test_range_response_with_its_byte_passes(self): + with range_server(b"x") as (url, ranges): + self.assertEqual(feed.http_content_length(url), 100) + self.assertEqual(ranges, ["bytes=0-0"]) + + def test_unsigned_enclosure_fails(self): + problems = check(Server({FEED_URL: appcast(enclosure(signature=""))}, {DMG: 100})) + self.assertEqual(problems, [f"{FEED_URL}: {DMG} has no sparkle:edSignature"]) + + def test_feed_without_items_fails(self): + problems = check(Server({FEED_URL: appcast()})) + self.assertEqual(problems, [f"{FEED_URL}: feed lists no item with an enclosure"]) + + def test_unparseable_feed_fails(self): + problems = check(Server({FEED_URL: b"Not Found"})) + self.assertEqual(len(problems), 1) + self.assertIn("does not parse as XML", problems[0]) + + def test_every_enclosure_is_checked(self): + arm = DMG.replace("cmux-macos.dmg", "cmux-macos-arm64.dmg") + server = Server({FEED_URL: appcast(enclosure(), enclosure(url=arm, length="50"))}, {DMG: 100}) + self.assertEqual(check(server), [f"{FEED_URL}: {arm} does not download (HTTP 404)"]) + + def test_transient_error_is_retried(self): + server = Server({FEED_URL: appcast(enclosure())}, {DMG: 100}, + failures={FEED_URL: ["HTTP 502"], DMG: ["connection reset"]}) + with patch.object(threading.Event, "wait", return_value=False): + self.assertEqual(check(server, attempts=3), []) + + def test_404_is_not_retried(self): + server = Server() + check(server, attempts=3) + self.assertEqual(server.calls, [("GET", FEED_URL)]) + + def test_cancelled_retry_window_starts_no_request(self): + cancelled = threading.Event() + cancelled.set() + window = feed.RetryWindow(10, cancelled=cancelled) + server = Server() + with self.assertRaises(feed.RetryCancelled): + feed.with_retries(3, server.get, FEED_URL, retry=window) + self.assertEqual(server.calls, []) + + def test_cancellation_during_backoff_starts_no_more_requests(self): + cancelled = threading.Event() + window = feed.RetryWindow(10, cancelled=cancelled) + server = Server(failures={FEED_URL: ["HTTP 502"]}) + + def cancel(_seconds): + cancelled.set() + return True + + with patch.object(cancelled, "wait", side_effect=cancel), \ + self.assertRaises(feed.RetryCancelled): + feed.with_retries(3, server.get, FEED_URL, retry=window) + self.assertEqual(server.calls, [("GET", FEED_URL)]) + + def test_request_retry_does_not_start_at_its_deadline(self): + clock = Clock() + cancelled = threading.Event() + server = Server(failures={FEED_URL: ["HTTP 502"]}) + with patch.object(feed.time, "monotonic", clock.monotonic), \ + patch.object(cancelled, "wait", side_effect=clock.sleep): + window = feed.RetryWindow(1, cancelled=cancelled) + with self.assertRaisesRegex(feed.FetchError, "HTTP 502"): + feed.with_retries(3, server.get, FEED_URL, retry=window) + self.assertEqual(server.calls, [("GET", FEED_URL)]) + self.assertEqual(clock.now, 1) + + def test_settle_cancellation_stops_feed_rounds(self): + cancelled = threading.Event() + + def cancel(_seconds): + cancelled.set() + return True + + with patch.object(feed, "check_feed", return_value=["HTTP 404"]) as check_url, \ + patch.object(cancelled, "wait", side_effect=cancel): + self.assertEqual(quiet_main_with_cancellation([ + "--feed", FEED_URL, "--settle-seconds", "60", + ], cancelled), 130) + self.assertEqual(check_url.call_count, 1) + + def test_cli_sigterm_cancels_verification(self): + """A real termination signal stops a CLI checking a broken local feed.""" + requested = threading.Event() + + class Handler(BaseHTTPRequestHandler): + def do_GET(self): + self.send_error(404) + requested.set() + + def log_message(self, *_args): + pass + + with ThreadingHTTPServer(("127.0.0.1", 0), Handler) as server: + thread = threading.Thread(target=server.serve_forever, daemon=True) + thread.start() + process = subprocess.Popen([ + sys.executable, str(SCRIPT), "--feed", f"http://127.0.0.1:{server.server_port}/feed.xml", + "--attempts", "1", "--settle-seconds", "60", + ], stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True) + try: + self.assertTrue(requested.wait(5), "CLI did not request the feed") + process.send_signal(signal.SIGTERM) + stdout, stderr = process.communicate(timeout=5) + self.assertEqual(process.returncode, 130, stderr) + self.assertIn("Feed verification cancelled", stdout) + finally: + if process.poll() is None: + process.kill() + process.communicate() + server.shutdown() + thread.join() + + def test_main_exits_nonzero_on_any_problem(self): + """The CLI exits nonzero if any selected feed remains broken.""" + original = feed.check_feed + feed.check_feed = lambda url, attempts, **_kwargs: [] if url.endswith("good.xml") else [f"{url}: bad"] + try: + self.assertEqual(quiet_main(["--feed", "https://x/good.xml"]), 0) + self.assertEqual(quiet_main(["--feed", "https://x/good.xml", "--feed", "https://x/bad.xml"]), 1) + finally: + feed.check_feed = original + + def test_tag_adds_the_release_feeds(self): + """Tag selection adds every architecture to the chosen default scope.""" + seen = [] + original = feed.check_feed + feed.check_feed = lambda url, attempts, **_kwargs: seen.append(url) or [] + try: + self.assertEqual(quiet_main(["--feed", "https://x/a.xml", "--tag", "v1.2.3"]), 0) + finally: + feed.check_feed = original + self.assertEqual(seen, ["https://x/a.xml"] + [ + f"https://github.com/manaflow-ai/cmux/releases/download/v1.2.3/{name}" for name in EXPECTED_FEED_NAMES]) + + def test_settle_retries_a_404_until_it_clears(self): + # GitHub serves a cached 404 for a just-uploaded asset for a few minutes. + results = [["https://x/a.xml: feed did not load (HTTP 404)"], []] + clock = Clock() + with patch.object(feed, "check_feed", side_effect=lambda url, attempts, **_kwargs: results.pop(0)), \ + patch.object(feed.time, "monotonic", clock.monotonic), \ + patch.object(threading.Event, "wait", side_effect=clock.sleep): + self.assertEqual(quiet_main(["--feed", "https://x/a.xml", "--settle-seconds", "60"]), 0) + self.assertEqual(results, []) + + def test_settle_gives_up_at_the_deadline(self): + clock = Clock() + with patch.object(feed, "check_feed", return_value=["feed did not load (HTTP 404)"]), \ + patch.object(feed.time, "monotonic", clock.monotonic), \ + patch.object(threading.Event, "wait", side_effect=clock.sleep): + self.assertEqual(quiet_main(["--feed", "https://x/a.xml", "--settle-seconds", "60"]), 1) + self.assertEqual(clock.now, 60) + + def test_settle_retries_failing_feeds_in_rounds(self): + clock, calls = Clock(), [] + first, second, healthy = (f"https://x/{name}.xml" for name in ("a", "b", "healthy")) + + def check_url(url, _attempts, **_kwargs): + """Keep one feed failing while another recovers on its second call.""" + calls.append(url) + if url == healthy or (url == second and calls.count(second) > 1): + return [] + return [f"{url}: feed did not load (HTTP 404)"] + + with patch.object(feed, "check_feed", side_effect=check_url), \ + patch.object(feed.time, "monotonic", clock.monotonic), \ + patch.object(threading.Event, "wait", side_effect=clock.sleep): + self.assertEqual(quiet_main([ + "--feed", first, "--feed", second, "--feed", healthy, "--settle-seconds", "30", + ]), 1) + self.assertEqual(calls, [first, second, healthy, first, second]) + self.assertEqual(clock.now, 30) + + def test_settle_does_not_start_a_retry_after_the_deadline(self): + clock = Clock() + with patch.object(feed, "check_feed", return_value=["HTTP 404"]) as check_url, \ + patch.object(feed.time, "monotonic", clock.monotonic), \ + patch.object(threading.Event, "wait", side_effect=clock.sleep): + self.assertEqual(quiet_main(["--feed", FEED_URL, "--settle-seconds", "1"]), 1) + self.assertEqual(check_url.call_count, 1) + self.assertEqual(clock.now, 1) + + def test_zero_settle_checks_each_feed_once(self): + with patch.object(feed, "check_feed", return_value=["HTTP 404"]) as check_url: + self.assertEqual(quiet_main(["--feed", FEED_URL, "--feed", "https://x/b.xml"]), 1) + self.assertEqual(check_url.call_count, 2) + + def test_tag_only_checks_just_the_release_feeds(self): + """A backport checks all tagged architectures without probing latest.""" + seen = [] + original = feed.check_feed + feed.check_feed = lambda url, attempts, **_kwargs: seen.append(url) or [] + try: + self.assertEqual(quiet_main(["--tag", "v1.2.3", "--tag-only"]), 0) + finally: + feed.check_feed = original + self.assertEqual(seen, [ + f"https://github.com/manaflow-ai/cmux/releases/download/v1.2.3/{name}" for name in EXPECTED_FEED_NAMES]) + + def test_served_length_reads_the_range_total(self): + self.assertEqual(feed.served_length(206, "bytes 0-0/77859900", "1"), 77859900) + self.assertEqual(feed.served_length(200, None, "77859900"), 77859900) + self.assertIsNone(feed.served_length(206, "bytes 0-0/*", "1")) + self.assertIsNone(feed.served_length(200, None, None)) + + def test_default_feeds_cover_every_stable_feed_name(self): + """Each independently named architecture exists on both default hosts.""" + for name in EXPECTED_FEED_NAMES: + self.assertIn(f"https://github.com/manaflow-ai/cmux/releases/latest/download/{name}", feed.DEFAULT_FEEDS) + self.assertIn(f"https://files.cmux.com/stable/{name}", feed.DEFAULT_FEEDS) + + +if __name__ == "__main__": + unittest.main()