From 211fbe108f52643cf30f66d58c299e76ec2958dd Mon Sep 17 00:00:00 2001 From: Ulises Rayon <32680579+uncrayon@users.noreply.github.com> Date: Sun, 6 Sep 2026 00:43:47 -0600 Subject: [PATCH 1/5] Add coordinated release updates with proxy replacement and rollback --- .github/workflows/ci.yml | 14 ++ CHANGELOG.md | 9 +- README.md | 19 +- docs/backends.md | 4 +- docs/compatibility.md | 4 +- docs/hermes.md | 29 +++- docs/integration.md | 2 +- docs/updates.md | 131 ++++++++++++++ docs/validation.md | 21 +++ pyproject.toml | 7 +- scripts/test_update_release.py | 145 ++++++++++++++++ src/sloth_memory/__init__.py | 2 +- src/sloth_memory/cli.py | 10 +- src/sloth_memory/hermes.py | 43 ++++- src/sloth_memory/proxy.py | 36 +++- src/sloth_memory/releases.py | 87 ++++++++++ src/sloth_memory/update_compat.json | 1 + src/sloth_memory/updates.py | 258 ++++++++++++++++++++++++++++ tests/hermes/test_integration.py | 39 +++++ tests/test_archive.py | 45 +++++ tests/test_updates.py | 211 +++++++++++++++++++++++ 21 files changed, 1092 insertions(+), 25 deletions(-) create mode 100644 docs/updates.md create mode 100644 scripts/test_update_release.py create mode 100644 src/sloth_memory/releases.py create mode 100644 src/sloth_memory/update_compat.json create mode 100644 src/sloth_memory/updates.py create mode 100644 tests/test_updates.py diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index e695d66..3ff3ee9 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -47,6 +47,20 @@ jobs: with: name: python-distributions path: dist/* + updates: + runs-on: ${{ matrix.os }} + strategy: + fail-fast: false + matrix: + os: [ubuntu-latest, macos-latest, windows-latest] + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-python@v5 + with: + python-version: '3.12' + - run: python -m pip install build psutil packaging + - run: python -m build --wheel + - run: python scripts/test_update_release.py dist hermes: runs-on: ${{ matrix.os }} strategy: diff --git a/CHANGELOG.md b/CHANGELOG.md index b040fba..2f208d8 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,6 +1,13 @@ # Changelog -## 0.2.0.dev0 — unreleased +## 0.2.0a1 — coordinated release updates + +- Add `/sloth update check` and `/sloth update`, plus equivalent terminal commands. +- Verify official GitHub release wheel hashes and compatibility before installation; retain a rollback wheel and configuration backups. +- Drain inference and save resident state before proxy replacement, keep the model backend running, and verify the replacement before reopening inference. +- Roll back package and proxy on handled installation/startup failures; report recovery paths when rollback fails. +- Restart supported Hermes gateways through their native lifecycle after a successful package update; show installed, loaded, and running versions. +- Add isolated real-package upgrade and failed-start rollback acceptance. - Add the portable `/sloth` alias, preserve Telegram chat identity when parking, and document Telegram menu priority; cover dispatch and menu visibility in Hermes integration tests. diff --git a/README.md b/README.md index c59c585..bccfc81 100644 --- a/README.md +++ b/README.md @@ -6,12 +6,13 @@ sloth-memory saves a local model's conversation inference state to disk and rest it when you return. Built for people running open-weight models on their own hardware. MIT licensed. No cloud service or account. The portable runtime uses psutil. -**Current `main` · development version `0.2.0.dev0`.** Supports Linux, macOS, and +**Alpha release `0.2.0a1`.** Supports Linux, macOS, and Windows startup, automatic free-port selection, and routing adapters for llama.cpp, Ollama, vLLM, and MLX-LM. Disk park/resume through this adapter still requires the managed patched llama.cpp runtime and one slot. See [backend capabilities](docs/backends.md). -The published [alpha.2](https://github.com/uncrayon/sloth-memory/releases/tag/v0.1.0-alpha.2) -is the older Linux version; install from `main` below to test the merged changes. +Download the [current alpha](https://github.com/uncrayon/sloth-memory/releases/tag/v0.2.0a1). +Existing users: follow the [update guide](docs/updates.md), including the one-time +proxy replacement for installations older than this release. The service is independent of Hermes. A native Hermes adapter provides startup, slash-command onboarding, and cleanup controls. Other agents integrate through an HTTP proxy and explicit session metadata; a plain Python example is included. @@ -49,7 +50,7 @@ instead of creating the standalone environment below. Standalone installation on macOS/Linux: ```bash -git clone --branch main https://github.com/uncrayon/sloth-memory.git +git clone --branch v0.2.0a1 https://github.com/uncrayon/sloth-memory.git cd sloth-memory python3 -m venv .venv source .venv/bin/activate @@ -99,6 +100,16 @@ Storage defaults to `~/Library/Application Support/sloth-memory` on macOS, `XDG_DATA_HOME` overrides these. To change it, pass the **same** `--archive-dir` to the backend, proxy, and control commands. +## Updates + +In Hermes, use `/sloth update check` to compare installed, loaded, and running +versions, then `/sloth update` to install a published release. The updater saves +resident state, replaces its proxy, verifies health, and attempts rollback on +failure. Hermes gateways restart through their native restart lifecycle. + +For terminal use on any OS: `python -m sloth_memory update check` and +`python -m sloth_memory update`. See [updates and recovery](docs/updates.md). + ## Use with Hermes Install sloth-memory in Hermes' Python environment, enable it with diff --git a/docs/backends.md b/docs/backends.md index 9ea653a..d429049 100644 --- a/docs/backends.md +++ b/docs/backends.md @@ -1,7 +1,7 @@ # Backends and operating systems -This describes the current `main` development version (`0.2.0.dev0`). The published -alpha.2 remains Linux-only with its original llama.cpp integration. +This describes alpha `0.2.0a1`. Older alpha.2 installations retain their original +Linux-only scope until upgraded. ## Capability contract diff --git a/docs/compatibility.md b/docs/compatibility.md index 6884c7d..b60a853 100644 --- a/docs/compatibility.md +++ b/docs/compatibility.md @@ -1,7 +1,7 @@ # Runtime compatibility -This page describes the current `main` development version. See [backends](backends.md) -for routing capabilities; published alpha.2 retains its older Linux-only scope. +This page describes alpha `0.2.0a1`. See [backends](backends.md) for routing +capabilities. Older alpha.2 installations retain their original Linux-only scope. ## Runtime diff --git a/docs/hermes.md b/docs/hermes.md index c597000..be2be14 100644 --- a/docs/hermes.md +++ b/docs/hermes.md @@ -1,8 +1,7 @@ # Hermes adapter and onboarding -These instructions install the current `main` development version (`0.2.0.dev0`), -including portable startup and automatic port selection. The published alpha.2 -does not contain those changes. See [backend setup](backends.md) for capabilities. +These instructions install alpha `0.2.0a1`, including portable startup, automatic +port selection, and release updates. See [backend setup](backends.md) for capabilities. The adapter ships inside sloth-memory as a native Hermes plugin. It uses plugin discovery, request middleware, commands, and profile settings. It does not patch @@ -14,7 +13,7 @@ Install into **the same Python environment that runs Hermes**: ```bash # With your Hermes virtual environment activated: -git clone --branch main https://github.com/uncrayon/sloth-memory.git +git clone --branch v0.2.0a1 https://github.com/uncrayon/sloth-memory.git cd sloth-memory python -m pip install --upgrade . hermes plugins enable sloth-memory @@ -24,10 +23,11 @@ If Hermes asks whether the plugin may replace built-in tools, answer **No**. sloth-memory registers commands and middleware; it needs no tool overrides. Use `hermes plugins list --plain --no-bundled` to check that it is enabled. -For an existing checkout, use `git pull --ff-only origin main` on its `main` -branch, then repeat the pip install command. Run `sloth-memory --version` in -Hermes' environment to confirm `0.2.0.dev0`. Restart Hermes after installation or -upgrade to load the entry point. The adapter is tested against Hermes +For an existing installation, follow [updates and recovery](updates.md). Versions +older than `0.2.0a1` need a one-time package installation and proxy replacement; +subsequent releases can use `/sloth update`. Run `sloth-memory --version` in +Hermes' environment to confirm `0.2.0a1`. Restart Hermes after installation to +load the entry point. The adapter is tested against Hermes 0.21.0, upstream commit `9dd6634c5635321cf38840cc30e9b51226689128`. Use Python 3.11–3.13 for Hermes; the standalone service also supports 3.10/3.14. @@ -54,6 +54,19 @@ printed by the build; Windows typically places `llama-server.exe` under `runtime/build/bin/Release`. Onboarding does not download weights or compile a backend. Connecting an existing server in routing mode requires no build. +## Persistence and updates + +The installed package, plugin enablement, profile configuration, and saved slots +persist across a computer restart. When Hermes launches, the enabled plugin +starts its managed services if autostart is on. Starting Hermes itself at boot or +login is a separate Hermes service setting. The cleanup policy still expires old +snapshots; rebooting does not reset their age. + +A gateway restart reuses an existing compatible proxy so it does not interrupt +shared inference. It does not automatically replace that proxy's Python code. +Use `/sloth update check` to see all three versions and `/sloth update` for the +coordinated release update. See [updates and recovery](updates.md). + ## Guided setup `/sloth` is a shortcut for `/sloth-memory` on every platform. Use `/sloth` in diff --git a/docs/integration.md b/docs/integration.md index 44e77ef..c7f572c 100644 --- a/docs/integration.md +++ b/docs/integration.md @@ -85,7 +85,7 @@ Never publish keys, transcript files, or archive directories. `POST /_sloth/settings` atomically persists any subset of those settings. `POST /_sloth/cleanup` runs a manual sweep with the saved age/budget rules. Unknown keys, invalid booleans, negative ages, and nonpositive budgets are refused. -Status includes `service: "sloth-memory"` and `control_version: 2` for adapters. +Status includes the running package `version`, `maintenance`, `service: "sloth-memory"` and `control_version: 4` for adapters. ## Hermes diff --git a/docs/updates.md b/docs/updates.md new file mode 100644 index 0000000..84abacc --- /dev/null +++ b/docs/updates.md @@ -0,0 +1,131 @@ +# Updates and recovery + +Use these commands after installing `0.2.0a1` or newer: + +```text +/sloth update check +/sloth update +``` + +`check` is read-only. It reports the installed package, the adapter loaded in this +Hermes process, the running proxy, and the newest release available to the +installation's channel. An alpha installation includes prereleases; a stable +installation stays on stable releases. Only published releases with a matching +universal wheel and GitHub SHA-256 digest are offered. Installing from `main` +does not enable automatic tracking of new commits. Checks happen on command; +there is no background upgrade or notification schedule. + +`update` downloads and verifies the selected release, validates its Python, +dependency, snapshot-format, and updater-protocol compatibility, and backs up the +installed package and configuration. Dependencies must already satisfy the new +release; the updater does not change Hermes' other packages. There is no sudo +prompt: run it in a writable Python environment owned by the account running +Hermes. Editable installations must be updated from their source checkout. + +The proxy pauses new inference, waits up to 60 seconds for the current request, +and saves verified resident foreground state in native mode. If draining or +saving fails, the update stops before installing. During this brief maintenance +period, new inference receives HTTP 503 and should be retried after the update. +Routing mode preserves backend-managed state by retaining the backend process. + +After installation, the proxy is replaced at the same address, checked for the +expected version and backend health, and reopened. A busy address causes recovery +rather than silently changing a route during an update. The model binary, +weights, backend process, saved settings, and existing compatible slots are kept. +Saving resident state starts a new seven-day snapshot lifetime under the default +policy. Updating does not rebuild a patched runtime or migrate cache formats. + +In supported Hermes gateways, the command replies and then requests Hermes' +native draining restart, as `/restart` does. In an interactive Hermes CLI, or +when the gateway restart hook is unavailable, the reply tells you to restart +Hermes yourself. Reopen an interactive CLI after updating it. If several agents +or profiles share the Python environment, restart their other adapters and +update their proxies separately. `/sloth update check` shows a pending restart +until this adapter has loaded the installed version. + +From a terminal, with the same environment activated: + +```bash +python -m sloth_memory update check +python -m sloth_memory update +``` + +Pass `--archive-dir /your/archive` to either command for a custom archive. The +module invocation also works on Windows, where an active `sloth-memory.exe` +launcher cannot safely replace itself. Externally managed proxies must be +updated through their service owner. On shared bots, keep `/sloth` and +`/sloth-memory` restricted to administrators using Hermes' slash-command access +settings: these commands can install code in the bot's Python environment. + +## One-time upgrade from older alphas or development installs + +Old installations do not contain an updater or a proxy drain endpoint. A +package reinstall alone leaves their old proxy process running. To bootstrap: + +1. Stop Hermes and other clients of this proxy. For a managed Hermes gateway, + run `hermes gateway stop` from a separate terminal; close interactive clients. +2. Activate the Python environment that runs Hermes and install the release: + + ```bash + python -m pip install --upgrade https://github.com/uncrayon/sloth-memory/releases/download/v0.2.0a1/sloth_memory-0.2.0a1-py3-none-any.whl + ``` + +3. With all inference clients still stopped, save any resident state and stop + the old proxy. Set `archive` explicitly if you use a custom archive directory. + Use the proxy's `SLOTH_API_KEY` environment setting if authentication is enabled. + + ```python + from sloth_memory.cli import request + from sloth_memory.network import proxy_record + from sloth_memory.runtime import directory + from sloth_memory.updates import stop_proxy + + archive = directory() + record = proxy_record(archive) + if record: + status = request(record["base_url"], "status") + if status["activity"]["phase"] != "idle": + raise RuntimeError("Wait for inference to finish before upgrading") + if status.get("resident_key"): + request(record["base_url"], "park", {"key": status["resident_key"]}) + stop_proxy(record) + ``` + + Run this Python snippet with the same environment's interpreter. It validates + the recorded process identity before stopping it. Do not kill arbitrary + listeners on port 8080 or stop the model backend. + + The oldest alpha.2 proxy did not publish `proxy.json`. Stop that proxy through + the terminal or service that launched it after parking the conversation; an + absent record does not prove that an older proxy is stopped. + +4. Start Hermes again (`hermes gateway start` for a managed gateway). The enabled + plugin starts the new proxy and discovers its selected port. Run + `/sloth update check`; installed, loaded, and proxy versions should agree. + +## If an update fails + +For handled installation or replacement-startup failures, the updater attempts +to reinstall the previous wheel and restart its proxy. It reports `rolled_back` +only when recovery succeeds. `recovery_required` means manual attention is +needed; the error includes the backup directory. New inference remains paused +while a replacement is being verified; a surviving proxy's maintenance lease +expires after five minutes if the updater disappears unexpectedly. + +The archive's `update.json` records the last transaction. Backups are under +`updates//`, including the previous wheel, configuration copies, +and installation logs. They are private and are not part of seven-day snapshot +cleanup. Keep the latest successful rollback backup; older update backups can +be removed manually when no transaction is using them. + +A power loss or process kill during pip installation cannot guarantee automatic +rollback. From the same Python environment, reinstall the previous wheel named +in the backup directory, then restart Hermes: + +```bash +python -m pip install --no-index --no-deps --force-reinstall /path/to/backup/sloth_memory-PREVIOUS-py3-none-any.whl +``` + +This alpha does not apply configuration or snapshot-format migrations. A release +requiring them is refused with a pointer to its release notes rather than +silently invalidating saved state. diff --git a/docs/validation.md b/docs/validation.md index 8fab10d..1bcc099 100644 --- a/docs/validation.md +++ b/docs/validation.md @@ -1,5 +1,26 @@ # Alpha validation +## Coordinated updates — 0.2.0a1 + +Local release checks on September 6, 2026: + +- 75 Python tests: 74 passed, one optional model test skipped. +- 18 Hermes integration tests: 17 passed, one optional model test skipped, + against both the installed Hermes and pinned upstream source. +- Real wheel installation in a disposable Python 3.14 virtual environment: + upgrade succeeded; a subsequent package with a deliberately broken proxy + startup rolled back to the previous wheel and a healthy proxy. The proxy + address and upstream backend were retained. No production model was used. +- Tests cover maintenance gating, drain timeout, failed snapshot saves, invalid + release hashes/formats, wrong Python environments, interrupted installation, + failed replacement shutdown, and a lost acknowledgement when reopening traffic. +- Release wheel and source archive passed package metadata validation. + +The CI workflow repeats package upgrade and failed-start rollback acceptance on +Linux, macOS, and Windows. Native gateway restart scheduling is covered through +Hermes' real dispatch with the final restart operation mocked. This is separate +from the earlier live model park/resume evidence below. + ## Live Hermes migration — main development version On 2026-09-05, sloth-memory was installed into the existing Hermes Python 3.11 diff --git a/pyproject.toml b/pyproject.toml index 230b939..9718e4e 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -4,11 +4,11 @@ build-backend = "setuptools.build_meta" [project] name = "sloth-memory" -version = "0.2.0.dev0" +version = "0.2.0a1" description = "Let your local AI nap. Resume long conversations from saved inference state." readme = "README.md" requires-python = ">=3.10" -dependencies = ["psutil>=5.9"] +dependencies = ["psutil>=5.9", "packaging>=23"] license = {text = "MIT"} authors = [{name = "Ulises Rayon"}] keywords = ["llama.cpp", "kv-cache", "local-ai", "open-weights", "agents"] @@ -33,3 +33,6 @@ sloth-memory = "sloth_memory.hermes" [tool.setuptools.packages.find] where = ["src"] + +[tool.setuptools.package-data] +sloth_memory = ["update_compat.json"] diff --git a/scripts/test_update_release.py b/scripts/test_update_release.py new file mode 100644 index 0000000..2c8a4ad --- /dev/null +++ b/scripts/test_update_release.py @@ -0,0 +1,145 @@ +"""Exercise real pip upgrade/rollback in a disposable venv with a local HTTP backend. + +Usage: python scripts/test_update_release.py dist/sloth_memory-0.2.0a1-py3-none-any.whl +Requires the build environment to have psutil and packaging installed. No network. +""" + +import base64 +import csv +import hashlib +from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer +from importlib import metadata +import io +import json +import os +from pathlib import Path +import subprocess +import sys +import tempfile +import threading +import time +import venv +import zipfile + +import psutil +from packaging.version import Version + + +def variant(original, destination, version, *, broken=False): + rows = [] + with zipfile.ZipFile(original) as source, zipfile.ZipFile(destination, "w", zipfile.ZIP_DEFLATED) as wheel: + old = next(n.split("/")[0] for n in source.namelist() if n.endswith(".dist-info/METADATA")) + old_version = old[len("sloth_memory-"):-len(".dist-info")] + new = f"sloth_memory-{version}.dist-info" + for name in source.namelist(): + if name.endswith("/RECORD"): + continue + data = source.read(name) + if name.endswith("/METADATA") or name == "sloth_memory/__init__.py": + data = data.replace(old_version.encode(), version.encode()) + if broken and name == "sloth_memory/__main__.py": + data = b'import sys\nif "serve" in sys.argv: raise SystemExit(42)\n' + data + name = name.replace(old, new) + wheel.writestr(name, data) + digest = base64.urlsafe_b64encode(hashlib.sha256(data).digest()).rstrip(b"=").decode() + rows.append((name, "sha256=" + digest, str(len(data)))) + record = new + "/RECORD" + out = io.StringIO(newline="") + csv.writer(out).writerows([*rows, (record, "", "")]) + wheel.writestr(record, out.getvalue()) + + +class Backend(BaseHTTPRequestHandler): + def log_message(self, *args): + pass + + def do_GET(self): + body = b'{"status":"ok","data":[]}' + self.send_response(200) + self.send_header("Content-Length", str(len(body))) + self.end_headers() + self.wfile.write(body) + + +def main(): + wheel = Path(sys.argv[1]).resolve() + if wheel.is_dir(): + wheel, = wheel.glob("sloth_memory-*-py3-none-any.whl") + current = wheel.name.split("-")[1] + parsed = Version(current) + future = f"{parsed.major}.{parsed.minor}.{parsed.micro + 1}a1" + with tempfile.TemporaryDirectory(prefix="sloth-update-test-") as tmp: + root = Path(tmp) + venv.EnvBuilder(with_pip=True).create(root / "venv") + python = root / "venv" / ("Scripts/python.exe" if os.name == "nt" else "bin/python") + baseline = root / "sloth_memory-0.0.0-py3-none-any.whl" + broken = root / f"sloth_memory-{future}-py3-none-any.whl" + variant(wheel, baseline, "0.0.0") + variant(wheel, broken, future, broken=True) + subprocess.run([str(python), "-m", "pip", "install", "--no-index", "--no-deps", str(baseline)], check=True, + stdout=subprocess.DEVNULL) + site = Path(subprocess.check_output([str(python), "-c", "import sysconfig; print(sysconfig.get_path('purelib'))"], text=True).strip()) + dependencies = {str(metadata.distribution(name).locate_file("")) for name in ("psutil", "packaging")} + (site / "test-dependencies.pth").write_text("\n".join(dependencies) + "\n") + backend = ThreadingHTTPServer(("127.0.0.1", 0), Backend) + threading.Thread(target=backend.serve_forever, daemon=True).start() + archive = root / "archive" + archive.mkdir() + process = None + try: + with (root / "proxy.log").open("ab") as log: + process = subprocess.Popen([str(python), "-I", "-m", "sloth_memory", "serve", "--archive-dir", str(archive), + "--port", "18081", "--backend", "ollama", "--cache-mode", "routing", + "--upstream-url", f"http://127.0.0.1:{backend.server_port}"], stdout=log, stderr=log) + for _ in range(100): + if (archive / "proxy.json").exists(): + break + if process.poll() is not None: + raise RuntimeError((root / "proxy.log").read_text()) + time.sleep(.1) + original = json.loads((archive / "proxy.json").read_text()) + harness = root / "apply_update.py" + harness.write_text('''import hashlib, json, sys +from pathlib import Path +from unittest.mock import patch +from sloth_memory import releases, updates +wheel, archive, version, expected = sys.argv[1:] +wheel = Path(wheel) +release = dict(version=version, url="unused", name=wheel.name, sha256=hashlib.sha256(wheel.read_bytes()).hexdigest()) +with patch.object(releases, "latest", return_value=release), patch.object(releases, "fetch", return_value=wheel.read_bytes()): + try: + result = updates.apply(archive) + assert expected == "complete", result + except RuntimeError as exc: + assert expected == "rolled_back" and "rolled_back" in str(exc), str(exc) + result = json.loads((Path(archive) / "update.json").read_text()) +print(json.dumps({"state":result["state"], "version":result["version"]})) +''') + for candidate, version, expected in ((wheel, current, "complete"), (broken, future, "rolled_back")): + subprocess.run([str(python), "-I", str(harness), str(candidate), str(archive), version, expected], check=True) + actual = subprocess.check_output([str(python), "-I", "-m", "sloth_memory", "--version"], text=True).strip() + assert actual == current, actual + record = json.loads((archive / "proxy.json").read_text()) + assert record["base_url"] == original["base_url"] + assert record["upstream_url"] == original["upstream_url"] + subprocess.run([str(python), "-I", "-m", "sloth_memory", "doctor", "--archive-dir", str(archive)], + stdout=subprocess.DEVNULL, check=True) + print("PASS: real package upgrade, failed-start rollback, stable proxy route, backend retained") + finally: + if (archive / "proxy.json").exists(): + record = json.loads((archive / "proxy.json").read_text()) + try: + current = psutil.Process(record["pid"]) + if current.create_time() == record["created_at"]: + current.terminate() + current.wait(10) + except psutil.NoSuchProcess: + pass + if process: + process.wait(10) + backend.shutdown() + backend.server_close() + + +if __name__ == "__main__": + main() diff --git a/src/sloth_memory/__init__.py b/src/sloth_memory/__init__.py index 45f6dcd..76ea0c2 100644 --- a/src/sloth_memory/__init__.py +++ b/src/sloth_memory/__init__.py @@ -1,3 +1,3 @@ """Persistent inference state for local open-weight models.""" -__version__ = "0.2.0.dev0" +__version__ = "0.2.0a1" diff --git a/src/sloth_memory/cli.py b/src/sloth_memory/cli.py index 2a8644e..45cfc5d 100644 --- a/src/sloth_memory/cli.py +++ b/src/sloth_memory/cli.py @@ -32,6 +32,9 @@ def main(): parser = argparse.ArgumentParser(description="Let your local AI nap. Save its work for later.") parser.add_argument("--version", action="version", version=__version__) sub = parser.add_subparsers(dest="command", required=True) + update = sub.add_parser("update", help="check or install an official release, retaining rollback files") + update.add_argument("action", nargs="?", choices=("check",)) + update.add_argument("--archive-dir") serve = sub.add_parser("serve", help="start the localhost inference proxy") serve.add_argument("--archive-dir") serve.add_argument("--port", type=int, default=8080) @@ -62,7 +65,12 @@ def main(): cmd.add_argument("--cleanup", action=argparse.BooleanOptionalAction, default=None) args = parser.parse_args() try: - if args.command == "serve": + if args.command == "update": + from . import updates + archive = directory(args.archive_dir) + result = updates.check(archive) if args.action == "check" else updates.apply(archive) + print(json.dumps(result, indent=2)) + elif args.command == "serve": if not 1 <= args.port <= 65535 or not 1 <= args.upstream_port <= 65535: parser.error("ports must be between 1 and 65535") from .retention import validate diff --git a/src/sloth_memory/hermes.py b/src/sloth_memory/hermes.py index faaffd8..b79fcb6 100644 --- a/src/sloth_memory/hermes.py +++ b/src/sloth_memory/hermes.py @@ -46,6 +46,10 @@ def __init__(self, ctx): self.home = Path(get_hermes_home()).resolve() self.namespace = "hermes:" + hashlib.sha256(str(self.home).encode()).hexdigest()[:16] + ":" self.service = Service(self.settings, self.persist_service) + self.gateway = None + + def capture_gateway(self, *, gateway=None, **kwargs): + self.gateway = gateway def persist_service(self, config): previous = self.settings() @@ -131,6 +135,7 @@ def onboarding(self): else: lines += ["Next: /sloth-memory start, then /sloth-memory connect to select this route for future sessions."] lines += ["Commands:", " status | park | delete [k-…] | slots", + " update check | update", " retention 7 | budget 32 | cleanup on|off|now", " base-url http://127.0.0.1:8080 | autostart on|off", "Setup also accepts --backend llama.cpp|ollama|vllm|mlx, --upstream-url, --model, --cache-mode native|routing,", @@ -223,6 +228,27 @@ def handle(self, raw_args): args = shlex.split(raw_args) action = args[0] if args else "setup" rest = args[1:] + if action == "update" and rest in ([], ["check"]): + from . import updates + config = self.settings() + if rest: + result = updates.check(config["archive_dir"], url=config["base_url"] if config["external"] else None) + lines = [f"Installed: {result['installed']} · Hermes loaded: {result['loaded']} · Proxy: {result['proxy']}"] + if result.get("check_error"): + lines.append("Release check unavailable: " + result["check_error"]) + else: + lines.append("Available: " + result["latest"] if result["available"] else "No newer compatible published release.") + if result.get("last_update"): + state = result["last_update"] + lines.append("Last update: " + state["state"] + ". " + state.get("note", "")) + if result["loaded"] != result["installed"]: + lines.append("Restart Hermes to load the installed adapter.") + return "\n".join(lines) + from hermes_cli import config as hermes_config + if hermes_config.is_managed(): + raise PermissionError("updates are managed by your administrator") + result = updates.apply(config["archive_dir"], hermes_home=self.home, external=config["external"]) + return f"sloth-memory {result['version']}: {result['note']}" if action in {"setup", "onboarding", "help"}: return self.configure(rest) if rest and action == "setup" else self.onboarding() if action == "base-url" and len(rest) == 1: @@ -265,7 +291,19 @@ def handle(self, raw_args): async def command(self, raw_args): try: - return await asyncio.to_thread(self.handle, raw_args) + result = await asyncio.to_thread(self.handle, raw_args) + if shlex.split(raw_args) == ["update"]: + from importlib.metadata import version + from . import __version__ + if version("sloth-memory") != __version__ and self.gateway is not None: + from gateway.restart import is_container_restart_context, is_gateway_supervisor_process + supervised = is_gateway_supervisor_process() or is_container_restart_context() + # Let the command response be sent before Hermes drains and + # restarts through the same lifecycle used by /restart. + asyncio.get_running_loop().call_later(2, lambda: self.gateway.request_restart( + detached=not supervised, via_service=supervised)) + result += " Hermes will restart shortly to load the new adapter." + return result except (OSError, ValueError, RuntimeError) as exc: return "sloth-memory: " + str(exc) finally: @@ -277,7 +315,8 @@ def register(ctx): for name in ("sloth", "sloth-memory"): ctx.register_command(name, adapter.command, description="Set up conversation slots, park, delete, and configure cleanup", - args_hint="setup | status | park | delete | cleanup | retention | base-url", argument_mode="text") + args_hint="setup | status | park | delete | cleanup | retention | base-url | update", argument_mode="text") + ctx.register_hook("pre_gateway_dispatch", adapter.capture_gateway) ctx.register_hook("pre_command", adapter.capture_command) ctx.register_middleware("llm_request", adapter.middleware) ctx.on_unload(adapter.service.closed.set) diff --git a/src/sloth_memory/proxy.py b/src/sloth_memory/proxy.py index 751f725..c19a4c5 100755 --- a/src/sloth_memory/proxy.py +++ b/src/sloth_memory/proxy.py @@ -20,6 +20,7 @@ from .backends import Backend from .platforms import fsync_directory, process_matches from .runtime import directory +from . import __version__ LISTEN_HOST = os.environ.get("SLOTH_HOST", "127.0.0.1") LISTEN_PORT = int(os.environ.get("SLOTH_PORT", "8080")) @@ -113,6 +114,7 @@ def __init__(self): self.current_prompt = None self.activity = {"phase": "idle", "key": None} self.runtime_error = None + self.maintenance_until = time.monotonic() + 300 if os.environ.get("SLOTH_UPDATE_START") == "1" else 0 self.displaced = {} self._snapshot = {} self.entries = {} @@ -355,12 +357,33 @@ def status(self): upstream=backend().url.split("://", 1)[1], archive_dir=str(ARCHIVE), archived=len(entries), entries=entries, total_gib=round(sum(v["bytes"] for v in snapshot["entries"].values()) / 1024**3, 3), - service="sloth-memory", control_version=3, upstream_url=backend().url, + service="sloth-memory", version=__version__, control_version=4, upstream_url=backend().url, + maintenance=self.maintenance_until > time.monotonic(), capabilities=backend().capabilities(), ttl_days=snapshot["retention"]["ttl_days"], max_gib=snapshot["retention"]["max_gib"], cleanup_enabled=snapshot["retention"]["cleanup_enabled"], cleanup_interval_seconds=3600, recent=[dict(e, ago_s=round(now-e["at"], 1)) for e in snapshot["recent"]]) + def prepare_update(self, timeout=60): + # Set the gate before waiting: queued and new requests must not start + # another generation between saving the resident state and replacement. + if self.maintenance_until > time.monotonic(): + raise RuntimeError("an update is already preparing this proxy") + self.maintenance_until = time.monotonic() + 300 + acquired = self.lock.acquire(timeout=timeout) + try: + if not acquired: + raise RuntimeError("inference is still active; retry the update after the reply") + if backend().snapshots and self.current_key: + self.park(key=self.current_key) + return dict(ok=True, maintenance=True) + except BaseException: + self.maintenance_until = 0 + raise + finally: + if acquired: + self.lock.release() + def doctor(self): # Do not queue a diagnostic behind a long generation or mutate ownership. if not self.lock.acquire(blocking=False): @@ -503,10 +526,18 @@ def log_message(self, fmt, *args): def control(self, method, path, body): try: + if (method != "GET" and ARCHIVE_STATE.maintenance_until > time.monotonic() + and path not in {CONTROL_PREFIX + "cancel-update", CONTROL_PREFIX + "prepare-update"}): + raise RuntimeError("sloth-memory is updating; retry shortly") if method == "GET" and path == CONTROL_PREFIX + "status": payload = ARCHIVE_STATE.status() elif method == "GET" and path == CONTROL_PREFIX + "doctor": payload = ARCHIVE_STATE.doctor() + elif method == "POST" and path == CONTROL_PREFIX + "prepare-update": + payload = ARCHIVE_STATE.prepare_update() + elif method == "POST" and path == CONTROL_PREFIX + "cancel-update": + ARCHIVE_STATE.maintenance_until = 0 + payload = dict(ok=True) elif method == "GET" and path == CONTROL_PREFIX + "settings": payload = ARCHIVE_STATE.status() payload = {k: payload[k] for k in ("ttl_days", "max_gib", "cleanup_enabled")} @@ -600,6 +631,9 @@ def relay(self, method): lock = ARCHIVE_STATE.lock if generation else contextlib.nullcontext() started_at = time.monotonic() with lock: + if generation and ARCHIVE_STATE.maintenance_until > time.monotonic(): + self.send_error(503, "sloth-memory is updating; retry shortly") + return archive_ready = backend().snapshots if generation and archive_ready: try: diff --git a/src/sloth_memory/releases.py b/src/sloth_memory/releases.py new file mode 100644 index 0000000..c1dea95 --- /dev/null +++ b/src/sloth_memory/releases.py @@ -0,0 +1,87 @@ +"""Discover and verify published packages from the project's fixed release source.""" + +import hashlib +from importlib import metadata +import json +from pathlib import Path +import re +import sys +from urllib.request import Request, urlopen +import zipfile + +from packaging.requirements import Requirement +from packaging.specifiers import SpecifierSet +from packaging.version import InvalidVersion, Version + +REPOSITORY = "https://github.com/uncrayon/sloth-memory" +RELEASES_API = "https://api.github.com/repos/uncrayon/sloth-memory/releases?per_page=100" +MAX_DOWNLOAD = 25 * 1024**2 + + +def fetch(url, limit=MAX_DOWNLOAD): + req = Request(url, headers={"User-Agent": "sloth-memory-updater", "Accept": "application/vnd.github+json"}) + with urlopen(req, timeout=30) as response: + data = response.read(limit + 1) + if len(data) > limit: + raise ValueError("release download exceeds the size limit") + return data + + +def latest(installed): + candidates = [] + for release in json.loads(fetch(RELEASES_API, 2 * 1024**2)): + tag = release.get("tag_name", "") + if release.get("draft") or not re.fullmatch(r"v[0-9][0-9A-Za-z.\-]*", tag): + continue + try: + version = Version(tag[1:]) + except InvalidVersion: + continue + if version.is_prerelease and not Version(installed).is_prerelease: + continue + name = f"sloth_memory-{version}-py3-none-any.whl" + for asset in release.get("assets", []): + url = f"{REPOSITORY}/releases/download/{tag}/{name}" + digest = asset.get("digest") or "" + if (asset.get("name") == name and asset.get("browser_download_url") == url + and re.fullmatch(r"sha256:[0-9a-f]{64}", digest)): + candidates.append(dict(version=str(version), url=url, sha256=digest[7:], + name=name, release_url=f"{REPOSITORY}/releases/tag/{tag}")) + return max(candidates, key=lambda item: Version(item["version"]), default=None) + + +def download(release, destination): + data = fetch(release["url"]) + if hashlib.sha256(data).hexdigest() != release["sha256"]: + raise ValueError("release checksum mismatch; nothing was installed") + path = Path(destination) / release["name"] + path.write_bytes(data) + try: + validate_wheel(path, release["version"]) + except (KeyError, TypeError, zipfile.BadZipFile) as exc: + raise ValueError("release wheel metadata is invalid; nothing was installed") from exc + return path + + +def validate_wheel(path, version): + from email.parser import BytesParser + with zipfile.ZipFile(path) as wheel: + info = BytesParser().parsebytes(wheel.read(f"sloth_memory-{version}.dist-info/METADATA")) + if info["Name"] != "sloth-memory" or Version(info["Version"]) != Version(version): + raise ValueError("release package identity mismatch") + compatibility = json.loads(wheel.read("sloth_memory/update_compat.json")) + if compatibility != {"updater_protocol": 1, "snapshot_format": 2, "control_version": 4}: + raise ValueError("this release requires a manual compatibility upgrade; see its release notes") + current_python = ".".join(map(str, sys.version_info[:3])) + if current_python not in SpecifierSet(info.get("Requires-Python", "")): + raise ValueError("this release needs a different Python version") + for raw in info.get_all("Requires-Dist", []): + requirement = Requirement(raw) + if requirement.marker and not requirement.marker.evaluate(): + continue + try: + installed = metadata.version(requirement.name) + except metadata.PackageNotFoundError: + installed = None + if requirement.url or installed is None or installed not in requirement.specifier: + raise ValueError(f"update dependency {requirement.name} in Hermes' environment first; nothing was installed") diff --git a/src/sloth_memory/update_compat.json b/src/sloth_memory/update_compat.json new file mode 100644 index 0000000..e4c0d10 --- /dev/null +++ b/src/sloth_memory/update_compat.json @@ -0,0 +1 @@ +{"updater_protocol": 1, "snapshot_format": 2, "control_version": 4} diff --git a/src/sloth_memory/updates.py b/src/sloth_memory/updates.py new file mode 100644 index 0000000..9acd391 --- /dev/null +++ b/src/sloth_memory/updates.py @@ -0,0 +1,258 @@ +"""Replace only sloth-memory, retaining a local wheel for rollback and the model process.""" + +import base64 +import csv +import hashlib +from importlib import metadata +import io +import json +import os +from pathlib import Path +import shutil +import subprocess +import sys +import threading +import time +import uuid +import zipfile + +import psutil +from packaging.version import Version + +from . import __version__ +from .cli import request +from .network import proxy_record +from .platforms import detached_options, file_lock, lock_file, process_matches +from . import releases + + +class ProxyStopError(RuntimeError): + """A replacement is still alive; do not change its package underneath it.""" + + +def write_json(path, value): + temporary = path.with_suffix(".tmp") + with temporary.open("w", encoding="utf-8") as out: + json.dump(value, out, indent=2) + out.flush() + os.fsync(out.fileno()) + temporary.replace(path) + + +def check(archive, *, url=None): + installed = metadata.version("sloth-memory") + record = proxy_record(Path(archive)) + address = url or (record["base_url"] if record else None) + try: + running = request(address, "status", timeout=5).get("version", "unknown (restart needed)") if address else "stopped" + except (OSError, ValueError, RuntimeError): + running = "unreachable" + result = dict(installed=installed, loaded=__version__, proxy=running) + state_file = Path(archive) / "update.json" + if state_file.exists(): + result["last_update"] = json.loads(state_file.read_text()) + state = result["last_update"] + if (state["state"] == "restart_required" and state["version"] == installed == __version__ + and running in (installed, "stopped")): + state.update(state="complete", note="This Hermes adapter has loaded the installed release.") + try: + release = releases.latest(installed) + result.update(latest=release["version"] if release else None, + available=bool(release and Version(release["version"]) > Version(installed)), + release_url=release["release_url"] if release else releases.REPOSITORY + "/releases") + except (OSError, ValueError) as exc: + result["check_error"] = str(exc) + return result + + +def rollback_wheel(destination): + """Repackage the installed distribution, including local patches, before pip replaces it.""" + dist = metadata.distribution("sloth-memory") + direct = json.loads(dist.read_text("direct_url.json") or "{}") + if direct.get("dir_info", {}).get("editable"): + raise ValueError("editable installations must be updated from their source checkout") + name = f"sloth_memory-{dist.version}" + path = destination / f"{name}-py3-none-any.whl" + rows = [] + with zipfile.ZipFile(path, "w", zipfile.ZIP_DEFLATED) as wheel: + for file in dist.files or []: + relative = file.as_posix() + if not relative.startswith(("sloth_memory/", name + ".dist-info/")): + continue + if "__pycache__" in relative or file.name in {"RECORD", "direct_url.json", "INSTALLER", "REQUESTED"}: + continue + data = dist.locate_file(file).read_bytes() + wheel.writestr(relative, data) + digest = base64.urlsafe_b64encode(hashlib.sha256(data).digest()).rstrip(b"=").decode() + rows.append((relative, "sha256=" + digest, str(len(data)))) + if not any(row[0] == "sloth_memory/__init__.py" for row in rows): + raise ValueError("cannot back up this installation; use its original package manager") + record = name + ".dist-info/RECORD" + output = io.StringIO(newline="") + csv.writer(output).writerows([*rows, (record, "", "")]) + wheel.writestr(record, output.getvalue()) + return path + + +def install(wheel, log): + env = {key: value for key, value in os.environ.items() if not key.startswith("PIP_")} + env["PIP_CONFIG_FILE"] = os.devnull + with log.open("ab") as out: + result = subprocess.run([sys.executable, "-I", "-m", "pip", "install", "--prefix", sys.prefix, "--no-input", "--no-index", + "--no-deps", "--force-reinstall", str(wheel)], + env=env, stdin=subprocess.DEVNULL, stdout=out, stderr=subprocess.STDOUT, timeout=120) + if result.returncode: + raise RuntimeError(f"package installation failed; details: {log}") + + +def stop_proxy(record): + if not process_matches(record): + raise RuntimeError("proxy process identity changed; refusing to stop it") + process = psutil.Process(record["pid"]) + process.terminate() + deadline = time.monotonic() + 15 + while process_matches(record): + try: + process.wait(.1) + return + except psutil.TimeoutExpired: + if time.monotonic() >= deadline: + raise RuntimeError("proxy did not stop; no force-kill was attempted") from None + + +def start_proxy(record, archive, env, version): + argv = [sys.executable, "-I", "-m", "sloth_memory", "serve", "--archive-dir", str(archive), + "--port", record["base_url"].rsplit(":", 1)[1], "--backend", record["backend"], + "--cache-mode", record["cache_mode"], "--upstream-url", record["upstream_url"]] + with (archive / "hermes-proxy.log").open("ab") as log: + child = subprocess.Popen(argv, env={**env, "SLOTH_UPDATE_START": "1"}, stdin=subprocess.DEVNULL, stdout=log, + stderr=subprocess.STDOUT, **detached_options()) + try: + for _ in range(100): + if child.poll() is not None: + raise RuntimeError("replacement proxy exited; inspect hermes-proxy.log") + current = proxy_record(archive) + if current and current["pid"] == child.pid: + status = request(current["base_url"], "status", timeout=5) + if current["base_url"] != record["base_url"] or status.get("version") != version: + raise RuntimeError("replacement proxy address or version did not match") + if not request(current["base_url"], "doctor", timeout=10)["ok"]: + raise RuntimeError("replacement proxy failed its health check") + threading.Thread(target=child.wait, daemon=True).start() + return current + time.sleep(.1) + raise RuntimeError("replacement proxy did not become ready") + except BaseException: + if child.poll() is None: + child.terminate() + try: + child.wait(15) + except subprocess.TimeoutExpired: + raise ProxyStopError(f"replacement PID {child.pid} did not stop; manual recovery required") from None + raise + + +def apply(archive, *, hermes_home=None, external=False): + if external: + raise ValueError("this proxy is externally managed; update it through its service owner") + if os.name == "nt" and sys.argv[0].lower().endswith("sloth-memory.exe"): + raise ValueError("on Windows use python -m sloth_memory update so the console launcher can be replaced") + archive = Path(archive) + archive.mkdir(parents=True, exist_ok=True, mode=0o700) + # One package environment can serve several profiles. Refuse concurrent + # installs even when those profiles use different archive directories. + fd = lock_file(Path(sys.prefix) / ".sloth-memory-update.lock") + try: + return _apply(archive, hermes_home) + finally: + os.close(fd) + + +def _apply(archive, hermes_home): + installed = metadata.version("sloth-memory") + release = releases.latest(installed) + newer = release and Version(release["version"]) > Version(installed) + existing = proxy_record(archive) + running = request(existing["base_url"], "status", timeout=5) if existing else {} + if not newer and (not existing or running.get("version") == installed): + return dict(state="current", version=installed, note="No newer compatible published release.") + target_version = release["version"] if newer else installed + stage = archive / "updates" / uuid.uuid4().hex + stage.mkdir(parents=True, mode=0o700) + wheel = releases.download(release, stage) if newer else None + backup = rollback_wheel(stage) + for source in [archive / "retention.json", *([Path(hermes_home) / "config.yaml"] if hermes_home else [])]: + if source.exists(): + shutil.copyfile(source, stage / (source.name + ".backup")) + (stage / (source.name + ".backup")).chmod(0o600) + state = dict(state="preparing", previous=installed, version=target_version, backup=str(stage)) + state_file = archive / "update.json" + write_json(state_file, state) + with file_lock(archive / ".hermes-start.lock"): + record = proxy_record(archive) + env = None + stopped = changed = prepared = False + try: + if record: + status = request(record["base_url"], "status", timeout=5) + if status.get("control_version", 0) < 4: + raise RuntimeError("the running proxy predates coordinated updates; follow the one-time upgrade in docs/updates.md") + process = psutil.Process(record["pid"]) + argv = process.cmdline() + if not process_matches(record) or argv[1:4] != ["-m", "sloth_memory", "serve"] and argv[1:5] != ["-I", "-m", "sloth_memory", "serve"]: + raise RuntimeError("proxy ownership could not be verified") + if Path(argv[0]).absolute() != Path(sys.executable).absolute(): + raise RuntimeError("proxy uses a different Python environment; update it separately") + env = process.environ() + request(record["base_url"], "prepare-update", {}, timeout=90) + prepared = True + stop_proxy(record) + stopped = True + state["state"] = "installing" + write_json(state_file, state) + if wheel: + changed = True # A failed pip call can already have uninstalled files. + install(wheel, stage / "install.log") + version = subprocess.check_output([sys.executable, "-I", "-m", "sloth_memory", "--version"], + text=True, timeout=15).strip() + if version != target_version: + raise RuntimeError("installed package failed its version check") + if record: + replacement = start_proxy(record, archive, env, version) + state.update(state="restart_required" if hermes_home else "complete", + note="Package and proxy updated. Restart Hermes to load its new adapter." if hermes_home + else "Package and proxy updated; restart other agents using this Python environment.") + write_json(state_file, state) + except BaseException as exc: + try: + if isinstance(exc, ProxyStopError): + raise exc + current = proxy_record(archive) + if stopped and current: + # The replacement stays in maintenance until commit. + stop_proxy(current) + if changed: + install(backup, stage / "rollback.log") + if stopped: + restored = start_proxy(record, archive, env, installed) + request(restored["base_url"], "cancel-update", {}, timeout=5) + elif prepared and process_matches(record): + request(record["base_url"], "cancel-update", {}, timeout=5) + state.update(state="rolled_back" if changed else "failed", note=str(exc)) + except Exception as recovery: + state.update(state="recovery_required", note=f"{exc}; recovery: {recovery}") + write_json(state_file, state) + if isinstance(exc, (KeyboardInterrupt, SystemExit)): + raise + raise RuntimeError(f"{state['state']}: {state['note']}. Backup: {stage}") from None + if record: + # A lost acknowledgement can mean inference is already reopened. + # Never stop a verified proxy or roll back after releasing this gate. + try: + request(replacement["base_url"], "cancel-update", {}, timeout=5) + except (OSError, ValueError, RuntimeError) as exc: + state.update(state="maintenance_pending", note=f"Release installed and verified, but reopening inference was not confirmed: {exc}") + write_json(state_file, state) + raise RuntimeError(state["note"] + ". The maintenance lease expires within five minutes.") from None + write_json(state_file, state) + return state diff --git a/tests/hermes/test_integration.py b/tests/hermes/test_integration.py index de51901..8040e82 100644 --- a/tests/hermes/test_integration.py +++ b/tests/hermes/test_integration.py @@ -97,6 +97,45 @@ def test_telegram_menu_priority_keeps_short_command_visible(self): self.assertIn("sloth", [name for name, _ in menu]) self.assertEqual(sum(name == "sloth" for name, _ in menu), 1) + def test_update_check_dispatches_without_installing_or_restarting(self): + from sloth_memory import updates + result = dict(installed="0.2.0a1", loaded="0.2.0a1", proxy="0.2.0a1", latest="0.2.0a2", available=True) + with patch.object(updates, "check", return_value=result), patch.object(updates, "apply") as install: + text = asyncio.run(self.gateway_command("update check", platform="telegram", command="sloth")) + self.assertIn("Available: 0.2.0a2", text) + install.assert_not_called() + + def test_successful_update_requests_native_gateway_restart_after_reply(self): + from unittest.mock import Mock + from hermes_cli.lifecycle import invoke_hook + from sloth_memory import updates + gateway = Mock() + invoke_hook("pre_gateway_dispatch", gateway=gateway) + async def command(): + loop = asyncio.get_running_loop() + with patch.object(loop, "call_later", wraps=loop.call_later) as later: + result = await self.gateway_command("update", command="sloth") + self.assertIn("restart shortly", result) + gateway.request_restart.assert_not_called() + callback = next(call.args[1] for call in later.call_args_list if call.args[0] == 2) + callback() + gateway.request_restart.assert_called_once_with(detached=False, via_service=True) + with patch.object(updates, "apply", return_value=dict(version="0.2.0a2", note="Updated.")), \ + patch("importlib.metadata.version", return_value="0.2.0a2"), \ + patch("gateway.restart.is_gateway_supervisor_process", return_value=True): + asyncio.run(command()) + + def test_failed_update_never_requests_gateway_restart(self): + from unittest.mock import Mock + from hermes_cli.lifecycle import invoke_hook + from sloth_memory import updates + gateway = Mock() + invoke_hook("pre_gateway_dispatch", gateway=gateway) + with patch.object(updates, "apply", side_effect=RuntimeError("rolled_back")): + result = self.command_text("update") + self.assertIn("rolled_back", result) + gateway.request_restart.assert_not_called() + def test_discord_park_before_first_turn_explains_how_to_load_state(self): with patch.object(self.archive, "park") as park: result = asyncio.run(self.gateway_command("park")) diff --git a/tests/test_archive.py b/tests/test_archive.py index 65a44db..9cde9cc 100644 --- a/tests/test_archive.py +++ b/tests/test_archive.py @@ -15,6 +15,34 @@ class ArchiveTests(unittest.TestCase): + def test_update_saves_resident_state_and_gates_new_requests(self): + self.assertTrue(self.a.prepare_update()["ok"]) + self.assertIn(self.a.current_key, self.a.entries) + self.assertTrue(self.a.status()["maintenance"]) + + def test_update_save_failure_reopens_inference(self): + self.resume = False + with self.assertRaises(OSError): + self.a.prepare_update() + self.assertFalse(self.a.status()["maintenance"]) + self.assertFalse(self.a.entries) + + def test_update_wait_timeout_does_not_interrupt_generation(self): + held, release = threading.Event(), threading.Event() + def generation(): + with self.a.lock: + held.set() + release.wait(5) + thread = threading.Thread(target=generation) + thread.start() + self.addCleanup(thread.join) + self.addCleanup(release.set) + self.assertTrue(held.wait(1)) + with self.assertRaisesRegex(RuntimeError, "still active"): + self.a.prepare_update(timeout=.01) + self.assertFalse(self.a.status()["maintenance"]) + self.assertTrue(thread.is_alive()) + def setUp(self): self.tmp = tempfile.TemporaryDirectory() self.addCleanup(self.tmp.cleanup) @@ -245,6 +273,23 @@ def test_keys_are_not_truncated_or_derived_from_user_accounts(self): class RelayTests(unittest.TestCase): + def test_maintenance_rejects_generation_before_contacting_backend(self): + with tempfile.TemporaryDirectory() as tmp, patch.object(p, "ARCHIVE", Path(tmp)): + state = p.Archive() + state.maintenance_until = time.monotonic() + 60 + server = ThreadingHTTPServer(("127.0.0.1", 0), p.Handler) + threading.Thread(target=server.serve_forever, daemon=True).start() + self.addCleanup(server.server_close) + self.addCleanup(server.shutdown) + with patch.object(p, "ARCHIVE_STATE", state, create=True), patch.object(p.Handler, "forward") as forward: + conn = http.client.HTTPConnection("127.0.0.1", server.server_port, timeout=2) + self.addCleanup(conn.close) + conn.request("POST", "/v1/chat/completions", json.dumps({"messages": []})) + response = conn.getresponse() + self.assertEqual(response.status, 503) + response.read() + forward.assert_not_called() + def test_streaming_and_concurrent_requests_keep_slot_owned_until_eof(self): first_sent, release = threading.Event(), threading.Event() backend_order = [] diff --git a/tests/test_updates.py b/tests/test_updates.py new file mode 100644 index 0000000..f0cfdfe --- /dev/null +++ b/tests/test_updates.py @@ -0,0 +1,211 @@ +import hashlib +import json +import os +from pathlib import Path +import sys +import tempfile +import unittest +import zipfile +from unittest.mock import MagicMock, patch + +from sloth_memory import releases, updates + + +def release(version, **overrides): + name = f"sloth_memory-{version}-py3-none-any.whl" + return dict(tag_name="v" + version, draft=False, assets=[dict(name=name, + browser_download_url=f"{releases.REPOSITORY}/releases/download/v{version}/{name}", + digest="sha256:" + "a" * 64)], **overrides) + + +class ReleaseTests(unittest.TestCase): + def test_incompatible_snapshot_format_requires_manual_upgrade(self): + with tempfile.TemporaryDirectory() as tmp: + wheel = Path(tmp) / "package.whl" + with zipfile.ZipFile(wheel, "w") as out: + out.writestr("sloth_memory-0.2.0a2.dist-info/METADATA", "Name: sloth-memory\nVersion: 0.2.0a2\n") + out.writestr("sloth_memory/update_compat.json", json.dumps(dict(updater_protocol=1, snapshot_format=3, control_version=4))) + with self.assertRaisesRegex(ValueError, "manual compatibility"): + releases.validate_wheel(wheel, "0.2.0a2") + + def test_alpha_channel_and_stable_channel_do_not_downgrade(self): + data = [release("0.2.0a2"), release("0.2.0a10"), release("0.1.0")] + with patch.object(releases, "fetch", return_value=json.dumps(data).encode()): + self.assertEqual(releases.latest("0.2.0a1")["version"], "0.2.0a10") + self.assertEqual(releases.latest("0.1.0")["version"], "0.1.0") + + def test_drafts_unhashed_assets_and_foreign_sources_are_ignored(self): + draft = release("0.2.0a3"); draft["draft"] = True + unhashed = release("0.2.0a4"); unhashed["assets"][0]["digest"] = None + foreign = release("0.2.0a5"); foreign["assets"][0]["browser_download_url"] = "https://example.com/wheel" + with patch.object(releases, "fetch", return_value=json.dumps([draft, unhashed, foreign]).encode()): + self.assertIsNone(releases.latest("0.2.0a1")) + + def test_bad_checksum_never_reaches_wheel_validation(self): + with tempfile.TemporaryDirectory() as tmp, patch.object(releases, "fetch", return_value=b"bad"), patch.object(releases, "validate_wheel") as validate: + with self.assertRaisesRegex(ValueError, "checksum"): + releases.download(dict(url="unused", sha256="a" * 64, name="x.whl"), tmp) + validate.assert_not_called() + self.assertEqual(list(Path(tmp).iterdir()), []) + + +class UpdateTests(unittest.TestCase): + def setUp(self): + self.tmp = tempfile.TemporaryDirectory() + self.addCleanup(self.tmp.cleanup) + self.archive = Path(self.tmp.name) + self.events = [] + self.record = dict(pid=123, created_at=1, base_url="http://127.0.0.1:8123", + upstream_url="http://127.0.0.1:9123", backend="llama.cpp", cache_mode="native") + self.live = self.record + self.install_calls = 0 + self.install_error = None + self.start_error = None + self.new = dict(version="0.2.0a2") + self.mocks = {} + values = dict( + **{"metadata.version": lambda _: "0.2.0a1", "releases.latest": lambda _: self.new, + "releases.download": lambda r, stage: stage / "new.whl", + "rollback_wheel": lambda stage: stage / "old.whl", + "proxy_record": lambda _: self.live, "process_matches": lambda _: True, + "request": self.request, "install": self.install, "stop_proxy": self.stop, + "start_proxy": self.start, "subprocess.check_output": lambda *a, **kw: "0.2.0a2\n"}) + for name, value in values.items(): + mocked = patch("sloth_memory.updates." + name, side_effect=value).start() + self.addCleanup(patch.stopall) + self.mocks[name] = mocked + process = MagicMock() + process.cmdline.return_value = [sys.executable, "-m", "sloth_memory", "serve"] + process.environ.return_value = {} + self.process = patch("sloth_memory.updates.psutil.Process", return_value=process).start() + + def request(self, url, action, *args, **kwargs): + self.events.append(action) + return dict(control_version=4, version="0.2.0a1", ok=True) + + def install(self, wheel, log): + self.events.append(wheel.name) + self.install_calls += 1 + if self.install_calls == 1 and self.install_error: + raise self.install_error + + def stop(self, record): + self.events.append("stop") + self.live = None + + def start(self, record, archive, env, version): + self.events.append("start:" + version) + if version == "0.2.0a2" and self.start_error: + raise self.start_error + self.live = dict(record, pid=456) + return self.live + + def test_success_saves_before_stopping_and_keeps_backend(self): + result = updates._apply(self.archive, None) + self.assertEqual(result["state"], "complete") + self.assertLess(self.events.index("prepare-update"), self.events.index("stop")) + self.assertLess(self.events.index("stop"), self.events.index("new.whl")) + self.assertEqual(self.events[-1], "cancel-update") + self.assertEqual(self.mocks["stop_proxy"].call_count, 1) + self.assertEqual(self.mocks["start_proxy"].call_args.args[0]["upstream_url"], self.record["upstream_url"]) + + def test_failed_install_restores_package_and_proxy(self): + self.install_error = RuntimeError("pip failed") + with self.assertRaisesRegex(RuntimeError, "rolled_back"): + updates._apply(self.archive, None) + self.assertIn("old.whl", self.events) + self.assertIn("start:0.2.0a1", self.events) + self.assertEqual(self.events[-1], "cancel-update") + + def test_bad_new_proxy_restores_package_and_proxy(self): + self.start_error = RuntimeError("health failed") + with self.assertRaisesRegex(RuntimeError, "rolled_back"): + updates._apply(self.archive, None) + self.assertIn("old.whl", self.events) + self.assertIn("start:0.2.0a1", self.events) + + def test_keyboard_interrupt_recovers_before_propagating(self): + self.install_error = KeyboardInterrupt() + with self.assertRaises(KeyboardInterrupt): + updates._apply(self.archive, None) + self.assertIn("old.whl", self.events) + self.assertIn("start:0.2.0a1", self.events) + + def test_other_virtual_environment_is_not_stopped_or_installed(self): + self.process.return_value.cmdline.return_value[0] = str(self.archive / "other-python") + with self.assertRaisesRegex(RuntimeError, "different Python environment"): + updates._apply(self.archive, None) + self.mocks["stop_proxy"].assert_not_called() + self.mocks["install"].assert_not_called() + + def test_old_control_protocol_needs_bootstrap_without_touching_proxy(self): + self.mocks["request"].side_effect = lambda *a, **kw: dict(control_version=3) + with self.assertRaisesRegex(RuntimeError, "one-time upgrade"): + updates._apply(self.archive, None) + self.mocks["stop_proxy"].assert_not_called() + self.mocks["install"].assert_not_called() + + def test_no_update_does_not_reinstall_or_restart(self): + self.new = dict(version="0.2.0a1") + result = updates._apply(self.archive, None) + self.assertEqual(result["state"], "current") + self.mocks["stop_proxy"].assert_not_called() + self.mocks["install"].assert_not_called() + + def test_current_package_can_replace_an_older_running_proxy(self): + self.new = dict(version="0.2.0a1") + self.mocks["request"].side_effect = lambda *a, **kw: dict(control_version=4, version="0.2.0a0", ok=True) + self.mocks["subprocess.check_output"].side_effect = lambda *a, **kw: "0.2.0a1\n" + result = updates._apply(self.archive, None) + self.assertEqual(result["state"], "complete") + self.assertIn("start:0.2.0a1", self.events) + self.mocks["install"].assert_not_called() + + def test_surviving_replacement_blocks_package_rollback(self): + def start(*args): + self.live = dict(self.record, pid=456) + raise RuntimeError("replacement could not be stopped") + def stop(record): + if record["pid"] == 456: + raise RuntimeError("still alive") + self.stop(record) + self.mocks["start_proxy"].side_effect = start + self.mocks["stop_proxy"].side_effect = stop + with self.assertRaisesRegex(RuntimeError, "recovery_required"): + updates._apply(self.archive, None) + self.assertNotIn("old.whl", self.events) + + def test_unpublished_surviving_replacement_blocks_package_rollback(self): + self.start_error = updates.ProxyStopError("unpublished replacement still alive") + with self.assertRaisesRegex(RuntimeError, "recovery_required"): + updates._apply(self.archive, None) + self.assertNotIn("old.whl", self.events) + + def test_lost_reopen_ack_never_kills_a_verified_replacement(self): + def request(*args, **kwargs): + if args[1] == "cancel-update": + raise OSError("lost acknowledgement") + return self.request(*args, **kwargs) + self.mocks["request"].side_effect = request + with self.assertRaisesRegex(RuntimeError, "reopening inference"): + updates._apply(self.archive, None) + self.assertEqual(self.mocks["stop_proxy"].call_count, 1) + self.assertNotIn("old.whl", self.events) + + def test_pip_settings_cannot_redirect_install(self): + # Undo the transaction mock to exercise the subprocess boundary itself. + patch.stopall() + with patch.dict(os.environ, {"PIP_TARGET": "elsewhere", "PIP_USER": "1"}), patch.object(updates.subprocess, "run") as run: + run.return_value.returncode = 0 + updates.install(self.archive / "package.whl", self.archive / "install.log") + argv = run.call_args.args[0] + env = run.call_args.kwargs["env"] + self.assertEqual(argv[:4], [sys.executable, "-I", "-m", "pip"]) + self.assertEqual(argv[argv.index("--prefix") + 1], sys.prefix) + self.assertNotIn("PIP_TARGET", env) + self.assertNotIn("PIP_USER", env) + self.assertEqual(env["PIP_CONFIG_FILE"], os.devnull) + + +if __name__ == "__main__": + unittest.main() From 99dc330ecab983bb7864ce816d6e44ff2454792f Mon Sep 17 00:00:00 2001 From: Ulises Rayon <32680579+uncrayon@users.noreply.github.com> Date: Sun, 6 Sep 2026 00:47:25 -0600 Subject: [PATCH 2/5] Recognize Python environment path aliases across operating systems --- src/sloth_memory/updates.py | 12 +++++++++++- tests/test_updates.py | 14 ++++++++++++++ 2 files changed, 25 insertions(+), 1 deletion(-) diff --git a/src/sloth_memory/updates.py b/src/sloth_memory/updates.py index 9acd391..e29430c 100644 --- a/src/sloth_memory/updates.py +++ b/src/sloth_memory/updates.py @@ -30,6 +30,16 @@ class ProxyStopError(RuntimeError): """A replacement is still alive; do not change its package underneath it.""" +def same_python_environment(executable): + # Resolve aliases of the *directory* too (/var vs /private/var, Windows + # short paths), while keeping separate venvs that share one binary distinct. + try: + path = Path(executable) + return path.parent.samefile(Path(sys.executable).parent) and path.samefile(sys.executable) + except OSError: + return False + + def write_json(path, value): temporary = path.with_suffix(".tmp") with temporary.open("w", encoding="utf-8") as out: @@ -201,7 +211,7 @@ def _apply(archive, hermes_home): argv = process.cmdline() if not process_matches(record) or argv[1:4] != ["-m", "sloth_memory", "serve"] and argv[1:5] != ["-I", "-m", "sloth_memory", "serve"]: raise RuntimeError("proxy ownership could not be verified") - if Path(argv[0]).absolute() != Path(sys.executable).absolute(): + if not same_python_environment(argv[0]): raise RuntimeError("proxy uses a different Python environment; update it separately") env = process.environ() request(record["base_url"], "prepare-update", {}, timeout=90) diff --git a/tests/test_updates.py b/tests/test_updates.py index f0cfdfe..b6d62b2 100644 --- a/tests/test_updates.py +++ b/tests/test_updates.py @@ -49,6 +49,20 @@ def test_bad_checksum_never_reaches_wheel_validation(self): self.assertEqual(list(Path(tmp).iterdir()), []) +class EnvironmentTests(unittest.TestCase): + def test_alias_of_environment_is_allowed_but_shared_binary_is_not(self): + with tempfile.TemporaryDirectory() as tmp: + root = Path(tmp) + try: + (root / "alias").symlink_to(Path(sys.executable).parent, target_is_directory=True) + (root / "other").mkdir() + (root / "other" / Path(sys.executable).name).symlink_to(sys.executable) + except OSError: + self.skipTest("symlink creation is unavailable for this account") + self.assertTrue(updates.same_python_environment(root / "alias" / Path(sys.executable).name)) + self.assertFalse(updates.same_python_environment(root / "other" / Path(sys.executable).name)) + + class UpdateTests(unittest.TestCase): def setUp(self): self.tmp = tempfile.TemporaryDirectory() From b19c0c431884e8d8b654a643a0432d1c312f9969 Mon Sep 17 00:00:00 2001 From: Ulises Rayon <32680579+uncrayon@users.noreply.github.com> Date: Sun, 6 Sep 2026 00:50:16 -0600 Subject: [PATCH 3/5] Track the loaded Python environment across native launchers --- .github/workflows/ci.yml | 4 ++++ src/sloth_memory/proxy.py | 2 ++ src/sloth_memory/updates.py | 8 ++++++-- tests/test_updates.py | 5 +++++ 4 files changed, 17 insertions(+), 2 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 3ff3ee9..d6b4da1 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -1,7 +1,11 @@ name: CI on: push: + branches: [main] pull_request: +concurrency: + group: ci-${{ github.event.pull_request.number || github.ref }} + cancel-in-progress: true permissions: contents: read jobs: diff --git a/src/sloth_memory/proxy.py b/src/sloth_memory/proxy.py index c19a4c5..fecf706 100755 --- a/src/sloth_memory/proxy.py +++ b/src/sloth_memory/proxy.py @@ -12,6 +12,7 @@ import logging import os import re +import sys from pathlib import Path import threading import time @@ -746,6 +747,7 @@ def main(): from .platforms import process_identity server = bind_server(Handler, LISTEN_PORT, backend().url) atomic_json(ARCHIVE / "proxy.json", dict(**process_identity(os.getpid()), + python_prefix=str(Path(sys.prefix).resolve()), base_url=f"http://{LISTEN_HOST}:{server.server_port}", upstream_url=backend().url, backend=backend().name, cache_mode=backend().cache_mode)) log.info("Proxy listening at http://%s:%s → %s (%s)", LISTEN_HOST, server.server_port, backend().url, backend().cache_mode) diff --git a/src/sloth_memory/updates.py b/src/sloth_memory/updates.py index e29430c..5b0a7de 100644 --- a/src/sloth_memory/updates.py +++ b/src/sloth_memory/updates.py @@ -30,10 +30,14 @@ class ProxyStopError(RuntimeError): """A replacement is still alive; do not change its package underneath it.""" -def same_python_environment(executable): +def same_python_environment(executable, prefix=None): # Resolve aliases of the *directory* too (/var vs /private/var, Windows # short paths), while keeping separate venvs that share one binary distinct. try: + # macOS framework and Windows venv launchers can expose the underlying + # interpreter in argv. The proxy records the environment Python loaded. + if prefix: + return Path(prefix).samefile(sys.prefix) path = Path(executable) return path.parent.samefile(Path(sys.executable).parent) and path.samefile(sys.executable) except OSError: @@ -211,7 +215,7 @@ def _apply(archive, hermes_home): argv = process.cmdline() if not process_matches(record) or argv[1:4] != ["-m", "sloth_memory", "serve"] and argv[1:5] != ["-I", "-m", "sloth_memory", "serve"]: raise RuntimeError("proxy ownership could not be verified") - if not same_python_environment(argv[0]): + if not same_python_environment(argv[0], record.get("python_prefix")): raise RuntimeError("proxy uses a different Python environment; update it separately") env = process.environ() request(record["base_url"], "prepare-update", {}, timeout=90) diff --git a/tests/test_updates.py b/tests/test_updates.py index b6d62b2..ce98521 100644 --- a/tests/test_updates.py +++ b/tests/test_updates.py @@ -50,6 +50,11 @@ def test_bad_checksum_never_reaches_wheel_validation(self): class EnvironmentTests(unittest.TestCase): + def test_recorded_prefix_handles_framework_launchers(self): + self.assertTrue(updates.same_python_environment("framework-python", sys.prefix)) + with tempfile.TemporaryDirectory() as other: + self.assertFalse(updates.same_python_environment(sys.executable, other)) + def test_alias_of_environment_is_allowed_but_shared_binary_is_not(self): with tempfile.TemporaryDirectory() as tmp: root = Path(tmp) From 5373855faba299602e35835c8a953963ae60017a Mon Sep 17 00:00:00 2001 From: Ulises Rayon <32680579+uncrayon@users.noreply.github.com> Date: Sun, 6 Sep 2026 00:53:33 -0600 Subject: [PATCH 4/5] Track proxy launches through Windows virtual environment wrappers --- src/sloth_memory/proxy.py | 1 + src/sloth_memory/updates.py | 18 +++++++++++++----- 2 files changed, 14 insertions(+), 5 deletions(-) diff --git a/src/sloth_memory/proxy.py b/src/sloth_memory/proxy.py index fecf706..6f4a4af 100755 --- a/src/sloth_memory/proxy.py +++ b/src/sloth_memory/proxy.py @@ -748,6 +748,7 @@ def main(): server = bind_server(Handler, LISTEN_PORT, backend().url) atomic_json(ARCHIVE / "proxy.json", dict(**process_identity(os.getpid()), python_prefix=str(Path(sys.prefix).resolve()), + launch_token=os.environ.get("SLOTH_LAUNCH_TOKEN"), base_url=f"http://{LISTEN_HOST}:{server.server_port}", upstream_url=backend().url, backend=backend().name, cache_mode=backend().cache_mode)) log.info("Proxy listening at http://%s:%s → %s (%s)", LISTEN_HOST, server.server_port, backend().url, backend().cache_mode) diff --git a/src/sloth_memory/updates.py b/src/sloth_memory/updates.py index 5b0a7de..df35cec 100644 --- a/src/sloth_memory/updates.py +++ b/src/sloth_memory/updates.py @@ -121,7 +121,7 @@ def install(wheel, log): def stop_proxy(record): if not process_matches(record): - raise RuntimeError("proxy process identity changed; refusing to stop it") + return # The original exited. Never signal a process that reused its PID. process = psutil.Process(record["pid"]) process.terminate() deadline = time.monotonic() + 15 @@ -135,18 +135,21 @@ def stop_proxy(record): def start_proxy(record, archive, env, version): + launch_token = uuid.uuid4().hex argv = [sys.executable, "-I", "-m", "sloth_memory", "serve", "--archive-dir", str(archive), "--port", record["base_url"].rsplit(":", 1)[1], "--backend", record["backend"], "--cache-mode", record["cache_mode"], "--upstream-url", record["upstream_url"]] with (archive / "hermes-proxy.log").open("ab") as log: - child = subprocess.Popen(argv, env={**env, "SLOTH_UPDATE_START": "1"}, stdin=subprocess.DEVNULL, stdout=log, + child = subprocess.Popen(argv, env={**env, "SLOTH_UPDATE_START": "1", "SLOTH_LAUNCH_TOKEN": launch_token}, stdin=subprocess.DEVNULL, stdout=log, stderr=subprocess.STDOUT, **detached_options()) try: for _ in range(100): if child.poll() is not None: raise RuntimeError("replacement proxy exited; inspect hermes-proxy.log") current = proxy_record(archive) - if current and current["pid"] == child.pid: + # Windows' venv launcher may spawn the actual proxy under another + # PID. Match this launch, not just the launcher's process number. + if current and current.get("launch_token") == launch_token: status = request(current["base_url"], "status", timeout=5) if current["base_url"] != record["base_url"] or status.get("version") != version: raise RuntimeError("replacement proxy address or version did not match") @@ -158,10 +161,15 @@ def start_proxy(record, archive, env, version): raise RuntimeError("replacement proxy did not become ready") except BaseException: if child.poll() is None: - child.terminate() try: + parent = psutil.Process(child.pid) + for descendant in reversed(parent.children(recursive=True)): + stop_proxy(dict(pid=descendant.pid, created_at=descendant.create_time())) + child.terminate() child.wait(15) - except subprocess.TimeoutExpired: + except psutil.NoSuchProcess: + pass + except (subprocess.TimeoutExpired, psutil.Error, RuntimeError): raise ProxyStopError(f"replacement PID {child.pid} did not stop; manual recovery required") from None raise From 1a472f3abe2a81914b6bd50bea6a32994dbd3be0 Mon Sep 17 00:00:00 2001 From: Ulises Rayon <32680579+uncrayon@users.noreply.github.com> Date: Sun, 6 Sep 2026 00:55:47 -0600 Subject: [PATCH 5/5] Finalize portable update recovery and validation evidence --- docs/validation.md | 7 ++++--- src/sloth_memory/updates.py | 17 +++++++++++------ 2 files changed, 15 insertions(+), 9 deletions(-) diff --git a/docs/validation.md b/docs/validation.md index 1bcc099..b537caa 100644 --- a/docs/validation.md +++ b/docs/validation.md @@ -4,7 +4,7 @@ Local release checks on September 6, 2026: -- 75 Python tests: 74 passed, one optional model test skipped. +- 77 Python tests: 76 passed, one optional model test skipped. - 18 Hermes integration tests: 17 passed, one optional model test skipped, against both the installed Hermes and pinned upstream source. - Real wheel installation in a disposable Python 3.14 virtual environment: @@ -16,8 +16,9 @@ Local release checks on September 6, 2026: failed replacement shutdown, and a lost acknowledgement when reopening traffic. - Release wheel and source archive passed package metadata validation. -The CI workflow repeats package upgrade and failed-start rollback acceptance on -Linux, macOS, and Windows. Native gateway restart scheduling is covered through +Package upgrade and failed-start rollback acceptance passed in CI on Linux, +macOS, and Windows. Tests also cover Python environment aliases and native +launchers whose process differs from the running proxy. Native gateway restart scheduling is covered through Hermes' real dispatch with the final restart operation mocked. This is separate from the earlier live model park/resume evidence below. diff --git a/src/sloth_memory/updates.py b/src/sloth_memory/updates.py index df35cec..b053c23 100644 --- a/src/sloth_memory/updates.py +++ b/src/sloth_memory/updates.py @@ -162,13 +162,18 @@ def start_proxy(record, archive, env, version): except BaseException: if child.poll() is None: try: - parent = psutil.Process(child.pid) - for descendant in reversed(parent.children(recursive=True)): - stop_proxy(dict(pid=descendant.pid, created_at=descendant.create_time())) - child.terminate() + try: + descendants = psutil.Process(child.pid).children(recursive=True) + except psutil.NoSuchProcess: + descendants = [] + for descendant in reversed(descendants): + try: + stop_proxy(dict(pid=descendant.pid, created_at=descendant.create_time())) + except psutil.NoSuchProcess: + continue + if child.poll() is None: + child.terminate() child.wait(15) - except psutil.NoSuchProcess: - pass except (subprocess.TimeoutExpired, psutil.Error, RuntimeError): raise ProxyStopError(f"replacement PID {child.pid} did not stop; manual recovery required") from None raise