The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
test(e2e/git): git transport and working-tree edge cases through the real hermes update over smart HTTP
teknium159b14f69a046
diff --git a/tests/e2e/core/upgrade/git/__init__.py b/tests/e2e/core/upgrade/git/__init__.pynew file mode 100644index 00000000000..e69de29bb2ddiff --git a/tests/e2e/core/upgrade/git/_git_world.py b/tests/e2e/core/upgrade/git/_git_world.pynew file mode 100644index 00000000000..d72b2de05f8--- /dev/null+++ b/tests/e2e/core/upgrade/git/_git_world.py@@ -0,0 +1,251 @@+"""A real install served over real smart HTTP, and the real ``hermes update`` against it.++``World`` is one sandboxed machine (``_install_helpers.new_sandbox``: bwrap, empty fake HOME, the+git wrapper that reports the official remote URL) whose ``~/.gitconfig`` rewrites the official+GitHub URL to a loopback ``git http-backend`` origin (``_smart_http``). The install itself comes+from a real ``scripts/install.sh``: N-1's own copy for an N-1 install (it makes the depth-1+single-branch clone N-1 users have), HEAD's for a HEAD install (a ``--filter=tree:0`` clone).+``preclone`` seeds a checkout the installer then adopts, for the clone shapes users got another+way (a manual full clone, a ``blob:none`` fallback clone).++Everything a cell asserts is user-visible: the exit code and transcript of ``hermes update``, the+checkout's HEAD / branch / working tree / refs, the update receipt, and whether ``hermes+--version`` still answers. ``diag()`` renders all of it, plus the HTTP request log, for a failure+message that explains itself.+"""++from __future__ import annotations++import contextlib+import json+import os+import shutil+import subprocess+from concurrent.futures import ThreadPoolExecutor+from dataclasses import dataclass, field+from pathlib import Path+from typing import Callable, Iterator++import pytest++from tests.e2e.core.upgrade import _helpers as H+from tests.e2e.core.upgrade import _install_helpers as I+from tests.e2e.core.upgrade.git._smart_http import GitHTTPServer, serve_bare++REPO = "hermes-agent.git"+SUCCESS = "Update complete"+TRACEBACK = I.TRACEBACK++PYTESTMARK = [+ pytest.mark.platforms("linux"),+ # Every `hermes update` runs inside the bwrap sandbox against a throwaway install in tmp_path.+ pytest.mark.live_system_guard_bypass,+ pytest.mark.skipif(H.sandbox_required_reason() is not None, reason=str(H.sandbox_required_reason())),+ pytest.mark.skipif(shutil.which("git") is None, reason="git required"),+ pytest.mark.skipif(I.real_uv() is None, reason="uv required"),+]+++def output(cp: subprocess.CompletedProcess) -> str:+ return (cp.stdout or "") + (cp.stderr or "")+++def reported_success(cp: subprocess.CompletedProcess) -> bool:+ return cp.returncode == 0 or SUCCESS in output(cp)+++def n1_tag() -> str:+ """N-1: the newest release tag strictly before HEAD."""+ return I.git("describe", "--tags", "--abbrev=0", "--match", "v20[0-9][0-9].*", "HEAD~1", cwd=H.WORKTREE)+++def n1_base() -> str:+ """The commit an N-1 install sits on: N-1's tag, or ``HERMES_E2E_N1_REF`` (a patched commit+ object, used to prove red a cell whose bug lives in N-1's own updater code)."""+ return commit_of(os.environ.get("HERMES_E2E_N1_REF") or n1_tag())+++def commit_of(ref: str) -> str:+ return I.git("rev-parse", f"{ref}^{{commit}}", cwd=H.WORKTREE)+++def installer_script(ref: str | None) -> str:+ """``scripts/install.sh`` as of ``ref`` (None: this worktree's copy)."""+ if ref is None:+ return (H.WORKTREE / "scripts" / "install.sh").read_text(encoding="utf-8")+ return I.git("show", f"{ref}:scripts/install.sh", cwd=H.WORKTREE) + "\n"+++@dataclass+class World:+ root: Path+ srv: GitHTTPServer+ bare: Path+ sb: I.Sandbox+ transcripts: list[str] = field(default_factory=list)+ install_bytes: int = 0+ install_shape: dict[str, str] = field(default_factory=dict)++ # -- upstream ----------------------------------------------------------------------------+ def set_main(self, sha: str) -> None:+ I.git("update-ref", "refs/heads/main", sha, cwd=self.bare)++ def publish(self, message: str, files: dict[str, str]) -> str:+ """A new upstream commit on origin main (the release the user updates to)."""+ return I.publish_commit(self.bare, self.root, message, files)++ # -- the install ---------------------------------------------------------------------------+ @property+ def checkout(self) -> Path:+ return self.sb.checkout++ def git_env(self) -> dict[str, str]:+ """Host-side git with the sandbox's HOME: its URL rewrite, never the real GitHub."""+ return {"PATH": os.environ.get("PATH", "/usr/bin:/bin"), "HOME": str(self.sb.home),+ "GIT_CONFIG_NOSYSTEM": "1", "GIT_TERMINAL_PROMPT": "0", "LC_ALL": "C",+ "GIT_AUTHOR_NAME": "user", "GIT_AUTHOR_EMAIL": "[email protected]",+ "GIT_COMMITTER_NAME": "user", "GIT_COMMITTER_EMAIL": "[email protected]"}++ def git(self, *args: str, check: bool = True) -> str:+ return I.git(*args, cwd=self.checkout, check=check, env=self.git_env())++ def head(self) -> str:+ return self.git("rev-parse", "HEAD")++ def branch(self) -> str:+ return self.git("rev-parse", "--abbrev-ref", "HEAD")++ def config(self, key: str) -> str:+ return self.git("config", "--get", key, check=False)++ def shape(self) -> dict[str, str]:+ """The clone's shape: partial-clone filter and shallowness."""+ return {"promisor": self.config("remote.origin.promisor") or "-",+ "filter": self.config("remote.origin.partialclonefilter") or "-",+ "shallow": self.git("rev-parse", "--is-shallow-repository")}++ def status(self) -> str:+ return self.git("status", "--porcelain=v1", "--untracked-files=all")++ def refs(self, *patterns: str) -> list[str]:+ return self.git("for-each-ref", "--format=%(refname)", *patterns).split()++ def refs_containing(self, sha: str) -> list[str]:+ """Refs (branches, stash, backups, tags) that keep ``sha`` reachable; the reflog does not count."""+ return self.git("for-each-ref", "--contains", sha, "--format=%(refname)").split()++ def reset_clean(self) -> None:+ """Per-cell isolation on a shared install: on ``main`` at its current commit, a clean tree,+ no stash, no rescue refs, no git state files left by the previous cell."""+ for leftover in ("rebase-merge", "rebase-apply", "index.lock", "MERGE_HEAD"):+ p = self.checkout / ".git" / leftover+ if p.is_dir():+ shutil.rmtree(p)+ elif p.exists():+ p.unlink()+ self.git("checkout", "-q", "-f", "main")+ self.git("reset", "-q", "--hard", "refs/remotes/origin/main")+ self.git("clean", "-fdq")+ self.git("stash", "clear")+ for ref in self.refs("refs/hermes-update-backups", "refs/tags/pre-update-*"):+ self.git("update-ref", "-d", ref)+ assert not self.status(), f"reset_clean left a dirty tree:\n{self.status()}"++ def bytes_since(self, mark: int) -> int:+ return sum(r.body_bytes for r in self.srv.since(mark) if r.method == "POST")++ def update(self, *extra: str, timeout: float = 1200) -> subprocess.CompletedProcess:+ cp = self.sb.cli("update", "--yes", "--branch", "main", *extra, timeout=timeout)+ self.transcripts.append(f"$ hermes update --yes --branch main {' '.join(extra)} -> rc={cp.returncode}\n"+ f"{(cp.stdout or '')[-8000:]}\n{(cp.stderr or '')[-4000:]}")+ return cp++ def version(self) -> subprocess.CompletedProcess:+ return self.sb.cli("--version", timeout=180)++ def receipt(self) -> dict:+ path = self.sb.hermes_home / "logs" / "update_receipts" / "latest.json"+ if not path.is_file():+ return {}+ try:+ return json.loads(path.read_text(encoding="utf-8"))+ except (OSError, ValueError):+ return {"unreadable": str(path)}++ def diag(self, cp: subprocess.CompletedProcess | None = None, mark: int = 0) -> str:+ out = []+ if cp is not None:+ out.append(H.describe(cp, limit=8000))+ with contextlib.suppress(Exception):+ out.append(f"HEAD={self.head()} branch={self.branch()} shape={self.shape()}")+ out.append("status:\n" + (self.status() or " (clean)"))+ out.append("refs:\n" + self.git("for-each-ref", "--format=%(refname) %(objectname:short)",+ "refs/heads", "refs/stash", "refs/hermes-update-backups",+ "refs/remotes"))+ rec = self.receipt()+ if rec:+ out.append("receipt: " + json.dumps({k: rec.get(k) for k in ("outcome", "status", "exit_code", "steps")+ if k in rec}, default=str)[:3000])+ logs = self.sb.hermes_home / "logs"+ for name in ("update.log", "errors.log"):+ p = logs / name+ if p.is_file():+ out.append(f"--- {p} (tail)\n" + p.read_text(encoding="utf-8", errors="replace")[-3000:])+ out.append("http requests:\n" + self.srv.describe(mark))+ return "\n".join(out)+++def _preclone(sb: I.Sandbox, args: list[str], env: dict[str, str]) -> None:+ sb.hermes_home.mkdir(parents=True, exist_ok=True)+ cp = subprocess.run(["git", "clone", "-q", *args, "--branch", "main", I.OFFICIAL_HTTPS, str(sb.checkout)],+ capture_output=True, text=True, env=env, timeout=900)+ assert cp.returncode == 0, f"pre-clone {args} failed: {cp.stderr[-2000:]}"+++def world(root: Path, *, base: str, installer_ref: str | None = None,+ preclone: list[str] | None = None) -> Iterator[World]:+ """Serve origin ``main`` at ``base`` over smart HTTP and install from it with the installer+ of ``installer_ref`` (None: HEAD's). Yields the live ``World``; the server stops on exit."""+ root.mkdir(parents=True, exist_ok=True)+ srv_root = root / "srv"+ srv_root.mkdir(exist_ok=True)+ bare = serve_bare(srv_root, REPO, H.WORKTREE, base)+ with GitHTTPServer(srv_root) as srv:+ sb = I.new_sandbox(root / "sb")+ url = srv.url(REPO)+ (sb.home / ".gitconfig").write_text(+ f'[url "{url}"]\n insteadOf = {I.OFFICIAL_HTTPS}\n insteadOf = {I.OFFICIAL_SSH}\n'+ '[user]\n name = user\n email = [email protected]\n', encoding="utf-8")+ w = World(root=root, srv=srv, bare=bare, sb=sb)+ if preclone is not None:+ _preclone(sb, preclone, w.git_env())+ script = sb.root / "install.sh"+ script.write_text(installer_script(installer_ref), encoding="utf-8")+ cp = sb.run(["bash", str(script), "--non-interactive"], timeout=1800, input="")+ assert cp.returncode == 0, f"install ({installer_ref or 'HEAD'} installer, base {base[:12]}) failed:\n{w.diag(cp)}"+ head = w.head()+ assert head == base, f"installer left HEAD at {head}, expected {base}\n{w.diag(cp)}"+ w.install_bytes = w.bytes_since(0)+ w.install_shape = w.shape()+ yield w+++def start_world(root: Path, **kw) -> tuple[contextlib.AbstractContextManager, World]:+ """``world()`` entered by hand, for fixtures that build several installs concurrently."""+ cm = world(root, **kw)+ return cm, cm.__enter__()+++def in_parallel(jobs: dict[str, Callable[[], object]]) -> dict[str, object]:+ """Run independent scenarios concurrently; each value is the job's result or the exception it+ raised (re-raised by the cell that reads it, so one broken install fails only its own cells)."""+ out: dict[str, object] = {}+ with ThreadPoolExecutor(max_workers=len(jobs)) as pool:+ futures = {name: pool.submit(job) for name, job in jobs.items()}+ for name, fut in futures.items():+ try:+ out[name] = fut.result()+ except BaseException as exc: # noqa: BLE001 - handed to the cell+ out[name] = exc+ return outdiff --git a/tests/e2e/core/upgrade/git/_smart_http.py b/tests/e2e/core/upgrade/git/_smart_http.pynew file mode 100644index 00000000000..dfe6c1c0331--- /dev/null+++ b/tests/e2e/core/upgrade/git/_smart_http.py@@ -0,0 +1,337 @@+"""A real git smart-HTTP origin on loopback, with faults the test arms on command.++``git http-backend`` (the CGI git itself ships) runs behind a small threaded HTTP/1.1 server, so+the client under test speaks the real wire protocol (v2 over HTTP, partial-clone filters, shallow+negotiation, thin packs) exactly as it does against GitHub; a ``file://`` or ``--shared`` origin+never exercises any of that. The bare repositories it serves get ``uploadpack.allowFilter`` and+``uploadpack.allowAnySHA1InWant``.++Faults (``Fault``) are matched per request, in arming order, and consumed:++* ``status``: answer with that HTTP status (429/500/502/503...) before the backend runs;+* ``cut_after``: stream that many body bytes of the real response, then drop the connection+ without the terminating chunk (curl: "transfer closed with outstanding read data");+* ``stall_after``: stream that many body bytes, then go silent until released or ``stall_max``.++Every request is recorded (``requests``): method, path, v2 command, status, body bytes sent and+whether a fault fired, so a cell can bound what a retry downloaded.+"""++from __future__ import annotations++import gzip+import os+import shutil+import socket+import subprocess+import threading+import time+from dataclasses import dataclass, field+from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer+from pathlib import Path+from urllib.parse import urlsplit++_CHUNK = 64 * 1024+++@dataclass+class Fault:+ """One armed fault. ``path_has`` / ``command`` select the request; ``times`` how often it fires."""++ status: int | None = None+ cut_after: int | None = None+ stall_after: int | None = None+ stall_max: float = 600.0+ path_has: str = "git-upload-pack"+ method: str | None = None+ command: str | None = None # protocol-v2 command in the request body ("fetch", "ls-refs")+ times: int = 1+ skip: int = 0 # let this many matching requests through untouched first+ fired: int = 0+ seen: int = 0++ def matches(self, method: str, path: str, command: str | None) -> bool:+ if self.fired >= self.times:+ return False+ if self.path_has and self.path_has not in path:+ return False+ if self.method and self.method != method:+ return False+ return self.command is None or self.command == command+++@dataclass+class Request:+ method: str+ path: str+ command: str | None+ status: int = 0+ body_bytes: int = 0+ fault: str = ""+ at: float = field(default_factory=time.monotonic)+++def _v2_command(body: bytes) -> str | None:+ """First ``command=<name>`` pkt-line of a protocol-v2 request body."""+ i = 0+ while i + 4 <= len(body):+ try:+ n = int(body[i:i + 4], 16)+ except ValueError:+ return None+ if n < 4:+ i += 4+ continue+ line = body[i + 4:i + n].rstrip(b"\n")+ if line.startswith(b"command="):+ return line[len(b"command="):].decode("ascii", "replace")+ i += n+ return None+++class GitHTTPServer:+ """Serve bare repositories under ``root`` at ``http://127.0.0.1:<port>/<name>``."""++ def __init__(self, root: Path):+ self.root = Path(root)+ self.faults: list[Fault] = []+ self.requests: list[Request] = []+ self._lock = threading.Lock()+ self._release = threading.Event()+ self._git = shutil.which("git") or "git"+ server = self++ class Handler(BaseHTTPRequestHandler):+ protocol_version = "HTTP/1.1"++ def log_message(self, *_a): # quiet+ pass++ def do_GET(self):+ server._handle(self, b"")++ def do_POST(self):+ server._handle(self, self._read_body())++ def _read_body(self) -> bytes:+ if self.headers.get("Transfer-Encoding", "").lower() == "chunked":+ out = bytearray()+ while True:+ size = int(self.rfile.readline().split(b";")[0].strip() or b"0", 16)+ if size == 0:+ self.rfile.readline()+ return bytes(out)+ out += self.rfile.read(size)+ self.rfile.readline()+ return self.rfile.read(int(self.headers.get("Content-Length") or 0))++ self._httpd = ThreadingHTTPServer(("127.0.0.1", 0), Handler)+ self._httpd.daemon_threads = True+ self._thread = threading.Thread(target=self._httpd.serve_forever, daemon=True)++ # -- lifecycle -------------------------------------------------------------------------+ def __enter__(self) -> GitHTTPServer:+ self._thread.start()+ return self++ def __exit__(self, *exc) -> None:+ self._release.set()+ self._httpd.shutdown()+ self._httpd.server_close()++ @property+ def port(self) -> int:+ return self._httpd.server_address[1]++ def url(self, name: str) -> str:+ return f"http://127.0.0.1:{self.port}/{name}"++ # -- test controls ---------------------------------------------------------------------+ def arm(self, fault: Fault) -> Fault:+ with self._lock:+ self.faults.append(fault)+ self._release.clear()+ return fault++ def clear_faults(self) -> None:+ with self._lock:+ self.faults.clear()+ self._release.set()++ def mark(self) -> int:+ """Index into ``requests`` to slice what happened after this point."""+ with self._lock:+ return len(self.requests)++ def since(self, mark: int) -> list[Request]:+ with self._lock:+ return list(self.requests[mark:])++ def describe(self, mark: int = 0) -> str:+ return "\n".join(f" {r.method} {r.path} cmd={r.command} -> {r.status} {r.body_bytes}B {r.fault}"+ for r in self.since(mark)) or " (no requests)"++ # -- request handling ------------------------------------------------------------------+ def _take_fault(self, method: str, path: str, command: str | None) -> Fault | None:+ with self._lock:+ for f in self.faults:+ if f.matches(method, path, command):+ f.seen += 1+ if f.seen <= f.skip:+ continue+ f.fired += 1+ return f+ return None++ def _handle(self, h: BaseHTTPRequestHandler, raw_body: bytes) -> None:+ parts = urlsplit(h.path)+ body = raw_body+ if h.headers.get("Content-Encoding", "").lower() == "gzip" and raw_body:+ try:+ body = gzip.decompress(raw_body)+ except OSError:+ body = raw_body+ command = _v2_command(body) if h.command == "POST" else None+ rec = Request(h.command, parts.path, command)+ with self._lock:+ self.requests.append(rec)+ fault = self._take_fault(h.command, h.path, command)+ if fault is not None and fault.status is not None:+ rec.status, rec.fault = fault.status, f"status {fault.status}"+ msg = f"injected {fault.status}\n".encode()+ h.send_response(fault.status)+ h.send_header("Content-Type", "text/plain")+ h.send_header("Content-Length", str(len(msg)))+ if fault.status == 429:+ h.send_header("Retry-After", "1")+ h.end_headers()+ h.wfile.write(msg)+ return+ env = {+ "PATH": os.environ.get("PATH", "/usr/bin:/bin"),+ "GIT_PROJECT_ROOT": str(self.root),+ "GIT_HTTP_EXPORT_ALL": "1",+ "GIT_CONFIG_NOSYSTEM": "1",+ "HOME": str(self.root),+ "REQUEST_METHOD": h.command,+ "PATH_INFO": parts.path,+ "QUERY_STRING": parts.query,+ "CONTENT_TYPE": h.headers.get("Content-Type", ""),+ "CONTENT_LENGTH": str(len(raw_body)),+ "REMOTE_ADDR": "127.0.0.1",+ "SERVER_PROTOCOL": "HTTP/1.1",+ }+ if h.headers.get("Git-Protocol"):+ env["GIT_PROTOCOL"] = h.headers["Git-Protocol"]+ env["HTTP_GIT_PROTOCOL"] = h.headers["Git-Protocol"]+ if h.headers.get("Content-Encoding"):+ env["HTTP_CONTENT_ENCODING"] = h.headers["Content-Encoding"]+ proc = subprocess.Popen([self._git, "http-backend"], env=env, stdin=subprocess.PIPE,+ stdout=subprocess.PIPE, stderr=subprocess.DEVNULL)+ feeder = threading.Thread(target=self._feed, args=(proc, raw_body), daemon=True)+ feeder.start()+ try:+ self._relay(h, proc, rec, fault)+ finally:+ if proc.poll() is None:+ proc.kill()+ proc.wait()+ feeder.join(timeout=5)++ @staticmethod+ def _feed(proc: subprocess.Popen, body: bytes) -> None:+ try:+ proc.stdin.write(body)+ proc.stdin.close()+ except (BrokenPipeError, OSError):+ pass++ def _relay(self, h: BaseHTTPRequestHandler, proc: subprocess.Popen, rec: Request, fault: Fault | None) -> None:+ out = proc.stdout+ status, headers = 200, []+ while True:+ line = out.readline()+ if not line or line in (b"\r\n", b"\n"):+ break+ name, _, value = line.decode("latin-1").partition(":")+ name, value = name.strip(), value.strip()+ if name.lower() == "status":+ status = int(value.split()[0])+ else:+ headers.append((name, value))+ rec.status = status+ h.send_response(status)+ for name, value in headers:+ if name.lower() not in ("content-length", "transfer-encoding", "connection"):+ h.send_header(name, value)+ h.send_header("Transfer-Encoding", "chunked")+ h.end_headers()+ limit = None+ if fault is not None:+ limit = fault.cut_after if fault.cut_after is not None else fault.stall_after+ sent = 0+ try:+ while True:+ want = _CHUNK if limit is None else max(0, min(_CHUNK, limit - sent))+ data = out.read1(want) if want else b""+ if want and not data:+ break+ if data:+ h.wfile.write(b"%x\r\n%s\r\n" % (len(data), data))+ sent += len(data)+ if limit is not None and sent >= limit:+ h.wfile.flush()+ rec.body_bytes = sent+ if fault.cut_after is not None:+ rec.fault = f"cut after {sent}B"+ self._abort(h)+ return+ rec.fault = f"stalled after {sent}B"+ self._release.wait(timeout=fault.stall_max)+ self._abort(h)+ return+ h.wfile.write(b"0\r\n\r\n")+ h.wfile.flush()+ except (BrokenPipeError, ConnectionResetError):+ rec.fault = rec.fault or "client went away"+ rec.body_bytes = sent++ @staticmethod+ def _abort(h: BaseHTTPRequestHandler) -> None:+ h.close_connection = True+ try:+ h.connection.shutdown(socket.SHUT_RDWR)+ except OSError:+ pass+++def serve_bare(root: Path, name: str, source: Path, ref: str) -> Path:+ """Create ``root/name``: a bare origin with only ``main`` (at ``ref``) and the release tags+ already merged into it, like the official repository looked when ``ref`` was its tip. It is+ configured for partial clone and any-SHA wants. The server borrows ``source``'s objects+ (``--shared``: no copy); the client still receives real packs over HTTP.++ ``HERMES_E2E_GIT_OBJECTS`` may name an extra complete object store: a developer checkout that+ is itself a partial clone lacks old blobs a full clone needs (CI's full checkout does not)."""+ bare = root / name+ subprocess.run(["git", "init", "-q", "--bare", str(bare)], check=True, capture_output=True)+ stores = [Path(subprocess.run(["git", "-C", str(source), "rev-parse", "--path-format=absolute",+ "--git-common-dir"], check=True, capture_output=True, text=True)+ .stdout.strip()) / "objects"]+ extra = os.environ.get("HERMES_E2E_GIT_OBJECTS")+ if extra:+ stores.append(Path(extra))+ (bare / "objects" / "info" / "alternates").write_text("".join(f"{s}\n" for s in stores), encoding="utf-8")+ tags = subprocess.run(["git", "-C", str(source), "for-each-ref", "--merged", ref,+ "--format=%(objectname) %(refname)", "refs/tags/v*"],+ check=True, capture_output=True, text=True).stdout.splitlines()+ stdin = f"update refs/heads/main {ref}\n" + "".join(+ f"update {line.split()[1]} {line.split()[0]}\n" for line in tags)+ subprocess.run(["git", "-C", str(bare), "update-ref", "--stdin"], input=stdin, text=True, check=True,+ capture_output=True)+ for args in (["symbolic-ref", "HEAD", "refs/heads/main"],+ ["config", "uploadpack.allowFilter", "true"],+ ["config", "uploadpack.allowAnySHA1InWant", "true"],+ ["config", "http.receivepack", "false"]):+ subprocess.run(["git", "-C", str(bare), *args], check=True, capture_output=True)+ return barediff --git a/tests/e2e/core/upgrade/git/test_foreign_state.py b/tests/e2e/core/upgrade/git/test_foreign_state.pynew file mode 100644index 00000000000..907a7dd0b81--- /dev/null+++ b/tests/e2e/core/upgrade/git/test_foreign_state.py@@ -0,0 +1,132 @@+"""Concurrent and foreign git state in the install, through a real ``hermes update``.++Users' checkouts carry state other tools left: an ``index.lock`` from a crashed (or a still+running) git, an abandoned interactive rebase, a detached HEAD from a ``git checkout <sha>``,+sometimes with work committed on it. One HEAD install over smart HTTP is shared; each cell seeds+one such state on a clean ``main``, publishes an upstream release and runs ``hermes update --yes``.++The property: the update either heals the state and lands on the release, or refuses with a+message naming the obstacle, leaving HEAD and the tree as they were and claiming nothing false;+in no case does the user's committed work end up reachable only from the reflog.+"""++from __future__ import annotations++import os+import time++import pytest++from tests.e2e.core._pending_fixes import known_failure+from tests.e2e.core.upgrade import _install_helpers as I+from tests.e2e.core.upgrade.git import _git_world as G++pytestmark = G.PYTESTMARK++[email protected](scope="module")+def w(tmp_path_factory):+ with G.world(tmp_path_factory.mktemp("git-foreign"), base=I.head_sha()) as world:+ yield world+++def _assert_healthy_success(w: G.World, cp, target: str) -> None:+ assert cp.returncode == 0 and G.SUCCESS in G.output(cp), f"update did not succeed:\n{w.diag(cp)}"+ assert w.head() == target and w.branch() == "main", \+ f"update reported success but HEAD={w.head()[:12]} on {w.branch()}, expected main@{target[:12]}:\n{w.diag(cp)}"+ assert not w.status(), f"update left the tree dirty:\n{w.diag(cp)}"+ version = w.version()+ assert version.returncode == 0 and G.TRACEBACK not in G.output(version), w.diag(version)+++def test_crashed_git_index_lock_is_healed(w):+ w.reset_clean()+ lock = w.checkout / ".git" / "index.lock"+ lock.write_text("", encoding="utf-8")+ old = time.time() - 3600 # a git that died an hour ago, not one running now+ os.utime(lock, (old, old))+ target = w.publish("release: e2e foreign stale lock", {"e2e-foreign-stale-lock.txt": "release\n"})++ cp = w.update()++ _assert_healthy_success(w, cp, target)+ assert not lock.exists(), f"stale index.lock survived a successful update:\n{w.diag(cp)}"+++def test_live_index_lock_is_refused_truthfully(w):+ w.reset_clean()+ before = w.head()+ lock = w.checkout / ".git" / "index.lock"+ lock.write_text("", encoding="utf-8") # fresh: another git may be mid-write right now+ w.publish("release: e2e foreign live lock", {"e2e-foreign-live-lock.txt": "release\n"})++ cp = w.update()++ out = G.output(cp)+ assert cp.returncode != 0 and G.SUCCESS not in out, f"update claimed success over a live index.lock:\n{w.diag(cp)}"+ assert "index.lock" in out, f"refusal does not name the lock:\n{w.diag(cp)}"+ assert w.head() == before and not w.status(), f"refusal moved HEAD or dirtied the tree:\n{w.diag(cp)}"+ assert lock.exists(), f"update deleted a lock another git may still hold:\n{w.diag(cp)}"+ with known_failure(r"claims .*history diverged",+ "gated on #124642: a ff-merge blocked by index.lock is reported as diverged history, "+ "a rescue ref is written and `git reset --hard` is advised"):+ assert "diverged" not in out and not w.refs("refs/hermes-update-backups"), (+ f"an index.lock refusal claims local history diverged (and writes a rescue ref):\n{w.diag(cp)}")+++def test_detached_head_at_an_older_commit_is_brought_back_to_main(w):+ w.reset_clean()+ w.git("checkout", "-q", "--detach", "HEAD~1")+ target = w.publish("release: e2e foreign detached", {"e2e-foreign-detached.txt": "release\n"})++ cp = w.update()++ _assert_healthy_success(w, cp, target)+++def test_work_committed_on_a_detached_head_stays_reachable(w):+ w.reset_clean()+ w.git("checkout", "-q", "--detach", "HEAD")+ (w.checkout / "e2e-detached-work.txt").write_text("work on a detached HEAD\n", encoding="utf-8")+ w.git("add", "-A")+ w.git("commit", "-q", "-m", "work committed on a detached HEAD")+ work = w.head()+ target = w.publish("release: e2e foreign detached work", {"e2e-foreign-detached-work.txt": "release\n"})++ cp = w.update()++ assert w.head() == target or cp.returncode != 0, f"update neither landed nor refused:\n{w.diag(cp)}"+ with known_failure(r"reachable only from the reflog",+ "gated on #124643: switching a detached HEAD to main leaves commits made on it "+ "reachable only from the reflog, and the output never mentions them"):+ assert w.refs_containing(work) or w.head() == work, (+ f"commit {work[:12]} made on the detached HEAD is reachable only from the reflog after the update:\n"+ f"{w.diag(cp)}")+++def test_abandoned_interactive_rebase_is_healed_or_refused(w):+ w.reset_clean()+ (w.checkout / "e2e-rebase-wip.txt").write_text("wip being reworded\n", encoding="utf-8")+ w.git("add", "-A")+ w.git("commit", "-q", "-m", "wip: my commit under interactive rebase")+ env = w.git_env()+ env["GIT_SEQUENCE_EDITOR"] = "sed -i 1s/^pick/edit/"+ I.git("rebase", "-i", "HEAD~1", cwd=w.checkout, env=env) # stops at "edit": HEAD detached mid-rebase+ assert (w.checkout / ".git" / "rebase-merge").is_dir(), "could not seed a stopped interactive rebase"+ before = w.head()+ target = w.publish("release: e2e foreign rebase", {"e2e-foreign-rebase.txt": "release\n"})++ cp = w.update()++ rebase_left = (w.checkout / ".git" / "rebase-merge").exists()+ if cp.returncode != 0:+ assert "rebase" in G.output(cp).lower(), f"refused without naming the rebase:\n{w.diag(cp)}"+ assert w.head() == before, f"refusal moved HEAD:\n{w.diag(cp)}"+ return+ assert w.head() == target and w.branch() == "main", f"update reported rc=0 but did not land:\n{w.diag(cp)}"+ with known_failure(r"rebase still in progress",+ "gated on #124644: update switches to main under a stopped rebase and leaves "+ ".git/rebase-merge, so a later `git rebase --abort` rolls the update back"):+ assert not rebase_left, (+ f"update succeeded but left a rebase still in progress (.git/rebase-merge); `git rebase --abort` "+ f"would now reset main to {before[:12]}:\n{w.diag(cp)}")diff --git a/tests/e2e/core/upgrade/git/test_local_modifications.py b/tests/e2e/core/upgrade/git/test_local_modifications.pynew file mode 100644index 00000000000..e05c7f431b1--- /dev/null+++ b/tests/e2e/core/upgrade/git/test_local_modifications.py@@ -0,0 +1,117 @@+"""Local modifications through a real ``hermes update``: tracked edits, untracked files, local commits.++One HEAD install (HEAD's ``scripts/install.sh``: a ``--filter=tree:0`` clone over smart HTTP) is+shared by the cells; each cell starts from a clean ``main`` (``World.reset_clean``), makes the+user's change, publishes one upstream release on top and runs ``hermes update --yes``.++The property is the user's: whatever the update does with their work, it is either back in the+working tree or left behind a ref the output names, and the final banner / exit code never says+"Update complete" while their patch sits parked in a stash.+"""++from __future__ import annotations++import pytest++from tests.e2e.core._pending_fixes import known_failure+from tests.e2e.core.upgrade import _install_helpers as I+from tests.e2e.core.upgrade.git import _git_world as G++pytestmark = G.PYTESTMARK++USER_LINE = "user patch: keep my local tweak\n"++[email protected](scope="module")+def w(tmp_path_factory):+ with G.world(tmp_path_factory.mktemp("git-localmods"), base=I.head_sha()) as world:+ yield world+++def _stash_texts(w: G.World, rel: str) -> list[str]:+ """``rel`` as recorded in every stash entry (tracked part, then the untracked-files parent),+ whitespace-stripped like every ``World.git`` output."""+ out = []+ for i in range(len(w.git("stash", "list").splitlines())):+ for spec in (f"stash@{{{i}}}:{rel}", f"stash@{{{i}}}^3:{rel}"):+ text = w.git("show", spec, check=False)+ if text:+ out.append(text)+ return out+++def test_non_conflicting_edits_and_untracked_files_are_restored(w):+ w.reset_clean()+ readme = w.checkout / "README.md"+ readme.write_text(readme.read_text(encoding="utf-8") + "\n" + USER_LINE, encoding="utf-8")+ notes = w.checkout / "my_notes.txt"+ notes.write_text("my own notes\n", encoding="utf-8")+ target = w.publish("release: e2e localmods clean", {"e2e-localmods-clean.txt": "release\n"})++ cp = w.update()++ assert cp.returncode == 0 and w.head() == target, f"update did not land on {target}:\n{w.diag(cp)}"+ assert USER_LINE in readme.read_text(encoding="utf-8"), f"tracked edit not restored:\n{w.diag(cp)}"+ assert notes.is_file() and notes.read_text(encoding="utf-8") == "my own notes\n", \+ f"untracked file not restored:\n{w.diag(cp)}"+ assert not w.git("stash", "list"), f"restored changes still parked in a stash:\n{w.diag(cp)}"+++def test_conflicting_patch_is_recoverable_and_never_reported_complete(w):+ w.reset_clean()+ readme = w.checkout / "README.md"+ readme.write_text(readme.read_text(encoding="utf-8") + "\n" + USER_LINE, encoding="utf-8")+ target = w.publish("release: e2e localmods conflict", {"README.md": "# upstream rewrote the README\n"})++ cp = w.update()++ assert w.head() == target, f"code update did not land:\n{w.diag(cp)}"+ in_tree = USER_LINE in readme.read_text(encoding="utf-8")+ parked = any(USER_LINE.strip() in t for t in _stash_texts(w, "README.md"))+ assert in_tree or parked, f"the user's patch is neither in the tree nor in any stash:\n{w.diag(cp)}"+ if parked and not in_tree:+ with known_failure(r"reported 'Update complete' .*while the user's patch is parked",+ "gated on #122557: a conflicting autostash is parked and the update still exits 0 "+ "with 'Update complete!'"):+ assert not G.reported_success(cp), (+ f"reported 'Update complete' (rc={cp.returncode}) while the user's patch is parked in a stash:\n"+ f"{w.diag(cp)}")+++def test_untracked_file_colliding_with_a_new_upstream_file_is_not_lost(w):+ w.reset_clean()+ rel = "e2e-localmods-collide.txt"+ mine = "USER PRIVATE CONTENT that upstream never saw\n"+ (w.checkout / rel).write_text(mine, encoding="utf-8")+ target = w.publish("release: e2e localmods collide", {rel: "upstream adds this path\n"})++ cp = w.update()++ assert w.head() == target, f"code update did not land:\n{w.diag(cp)}"+ in_tree = (w.checkout / rel).read_text(encoding="utf-8") == mine+ parked = any(t == mine.strip() for t in _stash_texts(w, rel))+ with known_failure(r"untracked file .* is gone",+ "gated on #124641: an untracked file at a path upstream adds is reported 'kept as-is', "+ "replaced by upstream's copy, and its autostash is dropped"):+ assert in_tree or parked, (+ f"the user's untracked file {rel} is gone: the tree has upstream's copy and no stash keeps it:\n"+ f"{w.diag(cp)}")+++def test_local_commit_on_main_is_kept_behind_a_named_ref(w):+ w.reset_clean()+ (w.checkout / "e2e-local-patch.txt").write_text("my local commit\n", encoding="utf-8")+ w.git("add", "-A")+ w.git("commit", "-q", "-m", "my local patch")+ local = w.head()+ target = w.publish("release: e2e localmods diverged", {"e2e-localmods-diverged.txt": "release\n"})++ cp = w.update()++ assert cp.returncode == 0 and w.head() == target, f"update did not land on {target}:\n{w.diag(cp)}"+ keepers = [r for r in w.refs_containing(local) if r != "refs/heads/main"]+ assert keepers, f"local commit {local[:12]} is reachable only from the reflog:\n{w.diag(cp)}"+ assert any(r.removeprefix("refs/") in G.output(cp) or r in G.output(cp) for r in keepers), (+ f"local commit {local[:12]} is kept by {keepers}, but the output never names that ref:\n{w.diag(cp)}")+ version = w.version()+ assert version.returncode == 0 and G.TRACEBACK not in G.output(version), w.diag(version)diff --git a/tests/e2e/core/upgrade/git/test_partial_clone.py b/tests/e2e/core/upgrade/git/test_partial_clone.pynew file mode 100644index 00000000000..7be46173a4c--- /dev/null+++ b/tests/e2e/core/upgrade/git/test_partial_clone.py@@ -0,0 +1,72 @@+"""Partial and full clones updated N-1 -> HEAD -> next release through the real ``hermes update``.++Users' checkouts come in several shapes: HEAD's installer makes a ``--filter=tree:0`` clone, its+throttled fallback a ``--filter=blob:none`` clone, and plenty of users cloned the repository+themselves (a full clone). Each shape is seeded as that clone of N-1 over smart HTTP, adopted by+N-1's own ``scripts/install.sh``, then updated twice: to HEAD (N-1's updater hands off to HEAD's),+and to one more upstream release (HEAD's updater end to end). The three installs run concurrently.++Property: both updates land and the install runs, and the clone keeps its shape: a partial clone+keeps its filter, and a full clone stays full. Converting a full clone to ``tree:0`` re-arms the+``pack-objects ... should_include_obj`` fetch crash for every later update (#124272, #124323).+"""++from __future__ import annotations++import pytest++from tests.e2e.core._pending_fixes import known_failure+from tests.e2e.core.upgrade import _install_helpers as I+from tests.e2e.core.upgrade.git import _git_world as G++pytestmark = G.PYTESTMARK++SHAPES = {+ "tree0": ["--filter=tree:0"],+ "blobless": ["--filter=blob:none"],+ "full": [],+}+++def _scenario(root, shape: str) -> dict:+ cm, w = G.start_world(root / shape, base=G.n1_base(), installer_ref=G.n1_tag(), preclone=SHAPES[shape])+ run = {"cm": cm, "w": w, "shape0": w.install_shape}+ w.set_main(I.head_sha())+ run["cp1"], run["head1"], run["shape1"] = w.update(), w.head(), w.shape()+ run["target2"] = w.publish(f"release: e2e partial {shape}", {f"e2e-partial-{shape}.txt": "release\n"})+ run["cp2"], run["head2"], run["shape2"] = w.update(), w.head(), w.shape()+ run["version"] = w.version()+ return run++[email protected](scope="module")+def runs(tmp_path_factory):+ root = tmp_path_factory.mktemp("git-partial")+ results = G.in_parallel({shape: (lambda s=shape: _scenario(root, s)) for shape in SHAPES})+ yield results+ for res in results.values():+ if isinstance(res, dict):+ res["cm"].__exit__(None, None, None)++[email protected]("shape", list(SHAPES))+def test_updates_land_and_the_clone_keeps_its_shape(runs, shape):+ run = runs[shape]+ if isinstance(run, BaseException):+ raise run+ w: G.World = run["w"]+ cp1, cp2 = run["cp1"], run["cp2"]+ assert run["shape0"]["shallow"] == "false" and (shape == "full") == (run["shape0"]["filter"] == "-"), \+ f"seeded the wrong clone shape for {shape}: {run['shape0']}"+ assert cp1.returncode == 0 and run["head1"] == I.head_sha(), f"N-1 -> HEAD update failed:\n{w.diag(cp1)}"+ assert G.TRACEBACK not in G.output(cp1), f"N-1 -> HEAD update printed a traceback:\n{w.diag(cp1)}"+ with known_failure(r"full clone was converted to a partial clone",+ "gated on #122353: the post-update tag fetch passes --filter=tree:0 and turns a full clone "+ "into a promisor clone (HEAD's post-swap code, so a fix flips this directly)"):+ assert run["shape1"] == run["shape0"], (+ f"{'the full clone was converted to a partial clone' if shape == 'full' else 'the clone changed shape'} "+ f"by the N-1 -> HEAD update: {run['shape0']} -> {run['shape1']}\n{w.diag(cp1)}")+ assert cp2.returncode == 0 and run["head2"] == run["target2"], f"HEAD -> next update failed:\n{w.diag(cp2)}"+ assert run["shape2"] == run["shape0"], f"the clone changed shape: {run['shape0']} -> {run['shape2']}\n{w.diag(cp2)}"+ version = run["version"]+ assert version.returncode == 0 and G.TRACEBACK not in G.output(version), w.diag(version)diff --git a/tests/e2e/core/upgrade/git/test_shallow_install.py b/tests/e2e/core/upgrade/git/test_shallow_install.pynew file mode 100644index 00000000000..734a1645b83--- /dev/null+++ b/tests/e2e/core/upgrade/git/test_shallow_install.py@@ -0,0 +1,155 @@+"""Shallow and stale installs through the real ``hermes update``.++N-1's ``scripts/install.sh`` clones ``--depth 1 --single-branch``: that is the checkout every+N-1 user has. Three installs run concurrently over smart HTTP:++* ``depth1``: N-1's own depth-1 install, updated to HEAD and then to one more release. The first+ update must not download the whole project history to move one release (#123254: on a real+ network that transfer hits the 300 s fetch cap, so a stale shallow install can never update), and+ the second must succeed after the first one unshallowed the clone (#124272: the unshallow applied+ ``--filter=tree:0`` to a clone whose objects sit in a non-promisor pack, and the next fetch dies+ in ``pack-objects ... should_include_obj``).+* ``checked``: the same install after three passive ``hermes update --check`` runs while upstream+ moved (each is a depth-1 fetch that appends a graft), then updated to HEAD. The history is+ shared, so the update must not claim orphan divergence (#105951's symptom).+* ``prefetched``: a HEAD install (non-shallow ``tree:0``) with a local commit, where the user ran+ ``git fetch --depth 1 origin main`` (the documented workaround for slow fetches) before+ ``hermes update``. The local commit shares history with upstream: it must stay recoverable, and+ the update must not declare orphan divergence (#123346).+"""++from __future__ import annotations++import pytest++from tests.e2e.core._pending_fixes import known_failure+from tests.e2e.core.upgrade import _install_helpers as I+from tests.e2e.core.upgrade.git import _git_world as G++pytestmark = G.PYTESTMARK++ORPHAN = "orphan divergence"+++def _depth1(root) -> dict:+ cm, w = G.start_world(root / "depth1", base=G.n1_base(), installer_ref=G.n1_tag())+ run = {"cm": cm, "w": w, "shape0": w.install_shape}+ w.set_main(I.head_sha())+ run["mark1"] = w.srv.mark()+ run["cp1"], run["head1"] = w.update(), w.head()+ run["fetches1"] = [r for r in w.srv.since(run["mark1"]) if r.command == "fetch"]+ run["target2"] = w.publish("release: e2e shallow next", {"e2e-shallow-next.txt": "release\n"})+ run["mark2"] = w.srv.mark()+ run["cp2"], run["head2"] = w.update(), w.head()+ run["version"] = w.version()+ return run+++def _checked(root) -> dict:+ cm, w = G.start_world(root / "checked", base=G.n1_base(), installer_ref=G.n1_tag())+ run = {"cm": cm, "w": w, "shape0": w.install_shape, "checks": []}+ between = I.git("rev-list", "--first-parent", f"{G.n1_base()}..{I.head_sha()}", cwd=I.H.WORKTREE).split()+ for k in (len(between) * 3 // 4, len(between) // 2, len(between) // 4):+ w.set_main(between[k])+ run["checks"].append(w.sb.cli("update", "--check", timeout=600))+ shallow = w.checkout / ".git" / "shallow"+ run["grafts"] = len(shallow.read_text(encoding="utf-8").split()) if shallow.is_file() else 0+ w.set_main(I.head_sha())+ run["cp1"], run["head1"] = w.update(), w.head()+ return run+++def _prefetched(root) -> dict:+ cm, w = G.start_world(root / "prefetched", base=I.head_sha())+ run = {"cm": cm, "w": w}+ (w.checkout / "e2e-local-before-prefetch.txt").write_text("my local commit\n", encoding="utf-8")+ w.git("add", "-A")+ w.git("commit", "-q", "-m", "my local patch")+ run["local"] = w.head()+ run["target"] = w.publish("release: e2e shallow prefetch", {"e2e-shallow-prefetch.txt": "release\n"})+ w.git("fetch", "-q", "--depth", "1", "origin", "main")+ run["prefetch_shape"] = w.shape()+ run["cp1"], run["head1"] = w.update(), w.head()+ return run++[email protected](scope="module")+def runs(tmp_path_factory):+ root = tmp_path_factory.mktemp("git-shallow")+ results = G.in_parallel({"depth1": lambda: _depth1(root), "checked": lambda: _checked(root),+ "prefetched": lambda: _prefetched(root)})+ yield results+ for res in results.values():+ if isinstance(res, dict):+ res["cm"].__exit__(None, None, None)+++def _run(runs, name) -> dict:+ run = runs[name]+ if isinstance(run, BaseException):+ raise run+ return run+++def test_stale_depth1_install_updates_without_fetching_the_whole_history(runs):+ run = _run(runs, "depth1")+ w: G.World = run["w"]+ cp1 = run["cp1"]+ assert run["shape0"]["shallow"] == "true", f"N-1's installer did not make a shallow clone: {run['shape0']}"+ assert cp1.returncode == 0 and run["head1"] == I.head_sha(), f"N-1 -> HEAD update failed:\n{w.diag(cp1, run['mark1'])}"+ main_fetch = run["fetches1"][0].body_bytes if run["fetches1"] else 0+ bound = 2 * w.install_bytes+ with known_failure(r"downloaded .* the depth-1 install itself",+ "gated on #123254: on a depth-1 install the updater's plain `git fetch origin main` "+ "negotiates away the shallow boundary and downloads ~the whole history (N-1's pre-swap "+ "fetch: flips once a fixed release is N-1)"):+ assert main_fetch <= bound, (+ f"moving one release, the update's main fetch downloaded {main_fetch} bytes, more than twice the "+ f"{w.install_bytes} bytes of the depth-1 install itself:\n{w.diag(cp1, run['mark1'])}")+++def test_second_update_after_the_unshallowing_update_succeeds(runs):+ run = _run(runs, "depth1")+ w: G.World = run["w"]+ cp1, cp2 = run["cp1"], run["cp2"]+ assert cp1.returncode == 0 and run["head1"] == I.head_sha(), f"N-1 -> HEAD update failed:\n{w.diag(cp1, run['mark1'])}"+ with known_failure(r"should_include_obj|pack-objects died",+ "gated on #124272: the first update's unshallow fetch applies --filter=tree:0 to a "+ "non-promisor clone; the next fetch crashes in pack-objects (HEAD's post-swap step)"):+ assert cp2.returncode == 0 and run["head2"] == run["target2"], (+ f"the update after the unshallowing update failed (rc={cp2.returncode}):\n"+ f"{G.output(cp2)[-1500:]}\n{w.diag(cp2, run['mark2'])}")+ version = run["version"]+ assert version.returncode == 0 and G.TRACEBACK not in G.output(version), w.diag(version)+++def test_passive_checks_do_not_push_the_next_update_into_orphan_divergence(runs):+ run = _run(runs, "checked")+ w: G.World = run["w"]+ cp1 = run["cp1"]+ for cp in run["checks"]:+ assert cp.returncode == 0 and G.TRACEBACK not in G.output(cp), f"`hermes update --check` failed:\n{w.diag(cp)}"+ assert cp1.returncode == 0 and run["head1"] == I.head_sha(), f"N-1 -> HEAD update failed:\n{w.diag(cp1)}"+ with known_failure(r"claims orphan divergence",+ "gated on #124645: each depth-1 `--check` still appends a graft the reflog pins "+ "(the #105951 prune restores them), and the next update resets as orphan divergence "+ "(N-1's own check and pull code: flips once a fixed release is N-1)"):+ assert ORPHAN not in G.output(cp1) and not w.refs("refs/hermes-update-backups/orphan-*"), (+ f"after {len(run['checks'])} passive checks ({run['grafts']} grafts in .git/shallow) the update "+ f"claims orphan divergence on a history it shares with upstream:\n{w.diag(cp1)}")+++def test_depth1_prefetch_never_turns_shared_history_into_orphan_divergence(runs):+ run = _run(runs, "prefetched")+ w: G.World = run["w"]+ cp1 = run["cp1"]+ assert run["prefetch_shape"]["shallow"] == "true", f"the --depth 1 pre-fetch did not graft: {run['prefetch_shape']}"+ assert cp1.returncode == 0 and run["head1"] == run["target"], f"update failed:\n{w.diag(cp1)}"+ keepers = w.refs_containing(run["local"])+ assert keepers, f"local commit {run['local'][:12]} is reachable only from the reflog:\n{w.diag(cp1)}"+ with known_failure(r"claims orphan divergence",+ "gated on #123346: after a --depth pre-fetch the grafted tip has no ancestry, and the "+ "update resets as orphan divergence instead of deepening and re-testing"):+ assert ORPHAN not in G.output(cp1) and not w.refs("refs/hermes-update-backups/orphan-*"), (+ f"after a --depth 1 pre-fetch the update claims orphan divergence and force-resets main "+ f"(local commit {run['local'][:12]} shares history with upstream):\n{w.diag(cp1)}")diff --git a/tests/e2e/core/upgrade/git/test_truthful_outcome.py b/tests/e2e/core/upgrade/git/test_truthful_outcome.pynew file mode 100644index 00000000000..d759abf91d8--- /dev/null+++ b/tests/e2e/core/upgrade/git/test_truthful_outcome.py@@ -0,0 +1,116 @@+"""Truthful outcome of ``hermes update`` when the git transport fails.++The origin is a real smart-HTTP ``git http-backend``; faults are injected at the HTTP layer, where+GitHub's own failures happen: 429 rate limiting, 5xx on the ref advertisement or the fetch, a+connection dropped mid-pack, and a drop during the promisor lazy fetch that a ``--filter=tree:0``+install makes while checking out the new release. One HEAD install is shared by the cells.++Property: a failed transfer is a non-zero exit with no success banner and no success receipt; the+install is left runnable on the commit it had, with a clean tree, and no false diagnosis. Once the+fault clears a plain retry heals, and repeated interrupted fetches do not make that retry re-download+a pathological amount (a byte bound against a clean update of the same shape, never wall time).+"""++from __future__ import annotations++import os+import time++import pytest++from tests.e2e.core._pending_fixes import known_failure+from tests.e2e.core.upgrade import _install_helpers as I+from tests.e2e.core.upgrade.git import _git_world as G+from tests.e2e.core.upgrade.git._smart_http import Fault++pytestmark = G.PYTESTMARK++FAULTS = {+ "429-on-fetch": lambda: Fault(status=429, command="fetch", times=99),+ "502-on-ref-advertisement": lambda: Fault(status=502, path_has="info/refs", times=99),+ "503-on-ls-refs": lambda: Fault(status=503, command="ls-refs", times=99),+ "cut-mid-pack": lambda: Fault(cut_after=150, command="fetch", times=99),+ # The commits arrive; the trees/blobs the tree:0 checkout then lazy-fetches are cut off.+ "cut-mid-checkout-lazy-fetch": lambda: Fault(cut_after=20000, command="fetch", skip=1, times=99),+}++[email protected](scope="module")+def w(tmp_path_factory):+ with G.world(tmp_path_factory.mktemp("git-truthful"), base=I.head_sha()) as world:+ yield world+++def _assert_failed_truthfully(w: G.World, cp, before: str, mark: int) -> None:+ out = G.output(cp)+ diag = w.diag(cp, mark)+ assert cp.returncode != 0, f"update exited 0 although the transfer failed:\n{diag}"+ assert G.SUCCESS not in out, f"success banner printed although the transfer failed:\n{diag}"+ assert w.receipt().get("outcome") != "success", f"receipt records success for a failed transfer:\n{diag}"+ assert w.head() == before and w.branch() == "main", f"failed update moved HEAD:\n{diag}"+ assert not w.status(), f"failed update left the tree dirty:\n{diag}"+ version = w.version()+ assert version.returncode == 0 and G.TRACEBACK not in G.output(version), \+ f"install not runnable after the failed update:\n{w.diag(version, mark)}"++[email protected]("fault", list(FAULTS))+def test_transport_failure_is_reported_as_failure(w, fault):+ w.reset_clean()+ w.srv.clear_faults()+ before = w.head()+ w.publish(f"release: e2e truthful {fault}", {f"e2e-truthful-{fault}.txt": "release\n"})+ armed = w.srv.arm(FAULTS[fault]())+ mark = w.srv.mark()++ cp = w.update()++ w.srv.clear_faults()+ assert armed.fired, f"the {fault} fault never fired; the cell exercised nothing:\n{w.diag(cp, mark)}"+ _assert_failed_truthfully(w, cp, before, mark)+ with known_failure(r"claims .*history diverged",+ "gated on #124642: a ff-merge that failed for a non-divergence reason (lazy fetch cut) is "+ "reported as diverged history, a rescue ref is written and `git reset --hard` is advised"):+ assert "diverged" not in G.output(cp) and not w.refs("refs/hermes-update-backups"), (+ f"a transport failure claims local history diverged (and writes a rescue ref):\n{w.diag(cp, mark)}")+++def test_retry_after_interrupted_fetches_heals_without_refetching_history(w):+ w.reset_clean()+ w.srv.clear_faults()+ # Baseline: a clean update of a one-file release, bytes as the server sent them.+ clean_target = w.publish("release: e2e truthful baseline", {"e2e-truthful-baseline.txt": "release\n"})+ mark = w.srv.mark()+ cp = w.update()+ assert cp.returncode == 0 and w.head() == clean_target, f"baseline update failed:\n{w.diag(cp, mark)}"+ baseline = w.bytes_since(mark)++ before = w.head()+ target = w.publish("release: e2e truthful after cuts", {"e2e-truthful-after-cuts.txt": "release\n"})+ # Every checkout lazy fetch is cut mid-pack (each leaves a dead temp pack behind); the commits+ # themselves arrive on the first attempt.+ w.srv.arm(Fault(cut_after=20000, command="fetch", skip=1, times=99))+ for attempt in range(3):+ mark = w.srv.mark()+ cp = w.update()+ assert cp.returncode != 0 and w.head() == before, f"interrupted attempt {attempt + 1} did not fail cleanly:\n" \+ f"{w.diag(cp, mark)}"+ w.srv.clear_faults()+ pack_dir = w.checkout / ".git" / "objects" / "pack"+ dead = sorted(p.name for p in pack_dir.glob("tmp_*"))+ assert dead, f"the interrupted fetches left no temp packs; the cell exercised nothing:\n{w.diag(cp, mark)}"+ old = time.time() - 3600 # the user retries later: dead transfers are past any in-flight window+ for p in pack_dir.glob("tmp_*"):+ os.utime(p, (old, old))++ mark = w.srv.mark()+ cp = w.update()++ healed = w.bytes_since(mark)+ assert cp.returncode == 0 and G.SUCCESS in G.output(cp) and w.head() == target, \+ f"retry after the fault cleared did not heal:\n{w.diag(cp, mark)}"+ assert healed <= baseline * 1.5 + 64 * 1024, (+ f"after 3 interrupted fetches the healing update downloaded {healed} bytes, vs {baseline} for a clean update "+ f"of the same shape: it re-fetched far more than the release:\n{w.diag(cp, mark)}")+ debris = sorted(p.name for p in pack_dir.glob("tmp_*") if p.stat().st_mtime <= old + 1)+ assert not debris, f"dead transfers' temp packs survived a successful update: {debris}\n{w.diag(cp, mark)}"