From dc01269969ddcec477045ff6609812dfa43a1249 Mon Sep 17 00:00:00 2001 From: ant1fr Date: Thu, 19 Nov 2026 13:36:58 +0100 Subject: [PATCH 1/4] chore: make CI hangs diagnosable A 20-minute job timeout, verbose pytest output and a faulthandler stack dump after 300 s, so the intermittent Python 3.11 hang names the test it stops on. Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01VzFCH4ztqBYejkvLvFgnaq --- .github/workflows/ci.yml | 3 ++- pyproject.toml | 2 ++ 2 files changed, 4 insertions(+), 1 deletion(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 33d4e32..c66fcbb 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -17,6 +17,7 @@ jobs: lint-test: name: Lint & test (Python ${{ matrix.python-version }}) runs-on: ubuntu-latest + timeout-minutes: 20 strategy: fail-fast: false matrix: @@ -47,7 +48,7 @@ jobs: run: mypy app - name: Pytest - run: pytest + run: pytest -v - name: Pytest (slow / performance) run: pytest -m slow diff --git a/pyproject.toml b/pyproject.toml index 090fd84..7620af0 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -84,6 +84,8 @@ known-first-party = ["app"] testpaths = ["tests"] asyncio_mode = "auto" asyncio_default_fixture_loop_scope = "function" +# Dump every thread's stack when one test runs longer than this (diagnoses CI hangs). +faulthandler_timeout = 300 addopts = "-ra -m 'not slow'" markers = ["slow: long-running performance tests (run with `pytest -m slow`)"] From 03d8d12181a4d4159ca4b74bd24b2499a1882cf0 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Thu, 19 Nov 2026 12:53:50 +0000 Subject: [PATCH 2/4] chore(deps): Bump actions/github-script Bumps the github-actions group with 1 update in the / directory: [actions/github-script](https://github.com/actions/github-script). Updates `actions/github-script` from 8 to 9 - [Release notes](https://github.com/actions/github-script/releases) - [Commits](https://github.com/actions/github-script/compare/v8...v9) --- updated-dependencies: - dependency-name: actions/github-script dependency-version: '9' dependency-type: direct:production update-type: version-update:semver-major dependency-group: github-actions ... Signed-off-by: dependabot[bot] --- .github/workflows/pr-labels.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/pr-labels.yml b/.github/workflows/pr-labels.yml index 3788783..c667486 100644 --- a/.github/workflows/pr-labels.yml +++ b/.github/workflows/pr-labels.yml @@ -17,7 +17,7 @@ jobs: pull-requests: write steps: - name: Apply the label - uses: actions/github-script@v8 + uses: actions/github-script@v9 with: script: | const title = context.payload.pull_request.title; From 2a1bdd124cf0ec510f75a2bdad7f9f558d51f387 Mon Sep 17 00:00:00 2001 From: ant1fr Date: Thu, 19 Nov 2026 14:06:31 +0100 Subject: [PATCH 3/4] feat: give each engine a stable instance id and a unique name - instance_id: random UUID generated once, kept in /data/instance.json - instance_name: INSTANCE_NAME or 'Smart Frame Engine ' - exposed on GET /api/health and in the Zeroconf TXT record; the mDNS service name is the instance name and registration may rename on conflict, so two engines on one LAN coexist - contract 1.1 (additive), openapi.json regenerated, package version 1.0.0rc2 Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01VzFCH4ztqBYejkvLvFgnaq --- .env.example | 4 ++ app/api/deps.py | 7 +++ app/api/routes/system.py | 10 +++- app/core/identity.py | 61 +++++++++++++++++++++++ app/core/settings.py | 11 +++++ app/main.py | 10 +++- app/services/discovery.py | 15 +++--- docs/API_CONTRACT.md | 17 ++++++- docs/openapi.json | 14 +++++- pyproject.toml | 2 +- tests/test_ambient_family.py | 2 +- tests/test_api_contract.py | 17 +++++-- tests/test_identity.py | 96 ++++++++++++++++++++++++++++++++++++ 13 files changed, 249 insertions(+), 17 deletions(-) create mode 100644 app/core/identity.py create mode 100644 tests/test_identity.py diff --git a/.env.example b/.env.example index c3dd0a0..4ac8447 100644 --- a/.env.example +++ b/.env.example @@ -42,6 +42,10 @@ SESSION_SECRET= PUBLIC_IMAGE_ENDPOINTS=true # Advertise _smartframe._tcp.local. over mDNS (Docker needs network_mode: host for it). ZEROCONF_ENABLED=true +# Name of this engine (mDNS service name, shown to clients). Default: "Smart Frame Engine" +# plus the first characters of its random id (kept in /data/instance.json), so two engines on +# one network never share a name. +INSTANCE_NAME= # Max size of uploaded/downloaded images, in MB. MAX_UPLOAD_MB=20 # Reject external image URLs (posters, album covers, Home Assistant pictures) resolving to diff --git a/app/api/deps.py b/app/api/deps.py index 7462d2f..3f37c92 100644 --- a/app/api/deps.py +++ b/app/api/deps.py @@ -9,6 +9,7 @@ from app.core.auth import AuthState from app.core.config_store import ConfigStore from app.core.history_store import HistoryStore +from app.core.identity import InstanceIdentity from app.core.security import URLPolicy from app.core.settings import EnvSettings from app.providers.immich import ImmichGateway, ImmichProvider, PeopleDirectory @@ -32,6 +33,11 @@ def get_auth_state(request: Request) -> AuthState: return cast(AuthState, request.app.state.auth_state) +def get_identity(request: Request) -> InstanceIdentity: + """This engine's stable id and name (initialized during app startup).""" + return cast(InstanceIdentity, request.app.state.identity) + + def get_config_store(request: Request) -> ConfigStore: """The runtime configuration store (initialized during app startup).""" return cast(ConfigStore, request.app.state.config_store) @@ -109,6 +115,7 @@ def get_people_directory(request: Request) -> PeopleDirectory: SettingsDep = Annotated[EnvSettings, Depends(get_settings)] AuthStateDep = Annotated[AuthState, Depends(get_auth_state)] +IdentityDep = Annotated[InstanceIdentity, Depends(get_identity)] ConfigStoreDep = Annotated[ConfigStore, Depends(get_config_store)] HistoryStoreDep = Annotated[HistoryStore, Depends(get_history_store)] CurrentImageStoreDep = Annotated[CurrentImageStore, Depends(get_current_image_store)] diff --git a/app/api/routes/system.py b/app/api/routes/system.py index 4670ad4..74793b6 100644 --- a/app/api/routes/system.py +++ b/app/api/routes/system.py @@ -15,6 +15,7 @@ CurrentImageStoreDep, DeliveryServiceDep, EphemeralServiceDep, + IdentityDep, SchedulerDep, SettingsDep, ) @@ -39,6 +40,11 @@ class HealthResponse(BaseModel): description="Oldest contract version still served; a client implementing contract N " "is compatible when min_api_version <= N <= api_version" ) + instance_id: str = Field( + description="Stable random UUID of this engine, generated once and kept in the data " + "volume; use it as the client-side unique key" + ) + instance_name: str = Field(description="Human-readable name (also the mDNS service name)") auth: Literal["open", "key", "password"] = Field( description="Credentials the other endpoints need (same values as the Zeroconf record)" ) @@ -95,12 +101,14 @@ class StatusResponse(BaseModel): @router.get("/health", response_model=HealthResponse, summary="Liveness probe") -async def health(auth: AuthStateDep) -> HealthResponse: +async def health(auth: AuthStateDep, identity: IdentityDep) -> HealthResponse: """Liveness plus the compatibility handshake, readable before any credential is set up.""" return HealthResponse( version=__version__, api_version=API_VERSION, min_api_version=MIN_API_VERSION, + instance_id=identity.instance_id, + instance_name=identity.instance_name, auth=auth.mode, capabilities=capability_names(), ) diff --git a/app/core/identity.py b/app/core/identity.py new file mode 100644 index 0000000..6761314 --- /dev/null +++ b/app/core/identity.py @@ -0,0 +1,61 @@ +"""Instance identity: a stable random ``instance_id`` and a human-readable ``instance_name``. + +The id is generated once, stored in ``/data/instance.json`` and never changes while the data +volume lives, so clients (Home Assistant, scripts) can use it as a stable key even when the +engine's address changes. It is random: not derived from the MAC address, the hostname or +anything else about the machine, so exposing it publicly leaks nothing. + +The name defaults to ``Smart Frame Engine `` so two engines on one +LAN advertise different mDNS names without any configuration; ``INSTANCE_NAME`` overrides it. +""" + +from __future__ import annotations + +import logging +import uuid +from dataclasses import dataclass +from pathlib import Path +from typing import Final + +from app.core.json_store import atomic_write_json, read_json + +logger = logging.getLogger(__name__) + +DEFAULT_NAME: Final = "Smart Frame Engine" +MAX_NAME_LENGTH: Final = 60 + + +@dataclass(frozen=True) +class InstanceIdentity: + """Who this engine is.""" + + instance_id: str + instance_name: str + + +def _valid_id(value: object) -> str | None: + if not isinstance(value, str): + return None + try: + return str(uuid.UUID(value)) + except ValueError: + return None + + +def default_name(instance_id: str) -> str: + """The unique default name built from the start of the id.""" + return f"{DEFAULT_NAME} {instance_id[:6]}" + + +def load_identity(path: Path, name_override: str = "") -> InstanceIdentity: + """Read the stored id (generating and persisting it on first run) and resolve the name.""" + raw = read_json(path, dict) + instance_id = _valid_id(raw.get("instance_id") if isinstance(raw, dict) else None) + if instance_id is None: + instance_id = str(uuid.uuid4()) + try: + atomic_write_json(path, {"instance_id": instance_id}) + except OSError as exc: # read-only volume: keep running with a per-process id + logger.warning("Cannot persist the instance id (%s); it will change on restart", exc) + name = " ".join(name_override.split())[:MAX_NAME_LENGTH] or default_name(instance_id) + return InstanceIdentity(instance_id=instance_id, instance_name=name) diff --git a/app/core/settings.py b/app/core/settings.py index b170012..c8890a1 100644 --- a/app/core/settings.py +++ b/app/core/settings.py @@ -75,6 +75,12 @@ class EnvSettings(BaseSettings): description="Advertise _smartframe._tcp.local. over mDNS (needs host networking in Docker)", ) + instance_name: str = Field( + default="", + description="Name of this engine (mDNS service name, shown to clients); " + "default 'Smart Frame Engine '", + ) + max_upload_mb: int = Field(default=20, ge=1, le=200, description="Max image size in MB") block_private_urls: bool = Field( default=False, @@ -207,6 +213,11 @@ def last_delivery_path(self) -> Path: """Location of the last successful frame delivery (what the frame shows).""" return self.data_dir / "last_delivery.json" + @property + def instance_path(self) -> Path: + """Stable random instance id (not a secret).""" + return self.data_dir / "instance.json" + @property def secrets_path(self) -> Path: """Generated secrets (API key, session signing key), readable by the owner only.""" diff --git a/app/main.py b/app/main.py index 6500a9e..d857e0c 100644 --- a/app/main.py +++ b/app/main.py @@ -39,6 +39,7 @@ from app.core.config_models import RuntimeConfig from app.core.config_store import ConfigStore from app.core.history_store import HistoryStore +from app.core.identity import load_identity from app.core.limits import MULTIPART_OVERHEAD_BYTES, BodySizeLimitMiddleware from app.core.logging_config import masking_filter, setup_logging from app.core.proxy import RootPathMiddleware @@ -110,6 +111,8 @@ async def lifespan(app: FastAPI) -> AsyncIterator[None]: activity.attach() _prepare_data_dir(settings) auth_state.load() + identity = load_identity(settings.instance_path, settings.instance_name) + app.state.identity = identity config_store = ConfigStore(settings.config_path, settings.runtime_seed()) config_store.load() @@ -206,13 +209,16 @@ async def _on_config_change(_: RuntimeConfig) -> None: version=__version__, root_path=settings.root_path, auth=auth_state.mode, + instance=identity.instance_name, + instance_id=identity.instance_id, ) await advertiser.start() config = config_store.config logger.info( - "Smart Frame Engine %s started (data_dir=%s, auth=%s, root_path=%r, panel=%s, " - "power_mode=%s, pending=%s, scheduler=%s)", + "Smart Frame Engine %s started (instance=%s, data_dir=%s, auth=%s, root_path=%r, " + "panel=%s, power_mode=%s, pending=%s, scheduler=%s)", __version__, + identity.instance_id, settings.data_dir, auth_state.mode, settings.root_path, diff --git a/app/services/discovery.py b/app/services/discovery.py index 62a8f11..e3c08c5 100644 --- a/app/services/discovery.py +++ b/app/services/discovery.py @@ -1,11 +1,12 @@ """mDNS / Zeroconf: advertise ``_smartframe._tcp.local.`` so other devices can find the engine. The record carries TXT properties ``version``, ``api_version``, ``min_api_version`` (the -compatibility handshake of ``docs/API_CONTRACT.md``), ``path`` (``ROOT_PATH``) and ``auth`` -(``open``, ``key`` or ``password``). The capability list is not mirrored (a TXT string is -capped at 255 bytes): clients read it from ``GET /api/health`` after discovery. -Advertising is best effort: any failure (no multicast -in a bridged container, no network...) is logged and ignored, the engine runs regardless. +compatibility handshake of ``docs/API_CONTRACT.md``), ``instance_id`` (stable random id), +``path`` (``ROOT_PATH``) and ``auth`` (``open``, ``key`` or ``password``). The service name is +the unique ``instance_name``. The capability list is not mirrored (a TXT string is capped at 255 +bytes): clients read it from ``GET /api/health`` after discovery. +Advertising is best effort: any failure (no multicast in a bridged container, no network...) +is logged and ignored, the engine runs regardless. In Docker, mDNS needs ``network_mode: host``. """ @@ -55,6 +56,7 @@ def __init__( api_version: int = API_VERSION, min_api_version: int = MIN_API_VERSION, instance: str = "Smart Frame Engine", + instance_id: str = "", zeroconf_factory: Callable[[], Any] = lambda: AsyncZeroconf(ip_version=IPVersion.V4Only), addresses: Callable[[], list[str]] = local_addresses, ) -> None: @@ -70,6 +72,7 @@ def __init__( "min_api_version": str(min_api_version), "path": root_path or "/", "auth": auth, + **({"instance_id": instance_id} if instance_id else {}), }, server=f"{host}.local.", parsed_addresses=addresses(), @@ -86,7 +89,7 @@ async def start(self) -> bool: """Advertise the service; ``False`` (logged) when it could not be registered.""" try: zeroconf = self._factory() - await zeroconf.async_register_service(self._info) + await zeroconf.async_register_service(self._info, allow_name_change=True) except Exception as exc: logger.warning("Zeroconf advertising disabled: %s: %s", type(exc).__name__, exc) return False diff --git a/docs/API_CONTRACT.md b/docs/API_CONTRACT.md index 5eb285e..29438f5 100644 --- a/docs/API_CONTRACT.md +++ b/docs/API_CONTRACT.md @@ -1,4 +1,4 @@ -# Smart Frame Engine API Contract (v1.0) +# Smart Frame Engine API Contract (v1.1) This is the contract between the engine and **external clients**: the Home Assistant integration, Node-RED flows, shell scripts, phone shortcuts. It says what a client can rely on @@ -17,9 +17,11 @@ every authentication mode), so it works before any key or password is configured ```json { "status": "ok", - "version": "1.0.0rc1", + "version": "1.0.0rc2", "api_version": 1, "min_api_version": 1, + "instance_id": "3f2b8c1e-5d0a-4c7e-9b61-0a1d2e3f4a5b", + "instance_name": "Smart Frame Engine 3f2b8c", "auth": "key", "capabilities": ["activity_log", "ambient_context", "display_immich", "..."] } @@ -31,6 +33,8 @@ every authentication mode), so it works before any key or password is configured | `version` | Engine release, [PEP 440](https://peps.python.org/pep-0440/) (`1.0.0`, `1.0.0rc1`). Informational: never gate behaviour on it, use `api_version` and `capabilities`. | | `api_version` | Integer contract version the engine speaks. Incremented **only on a breaking change**. It is `1` for every v1.x release. | | `min_api_version` | Oldest contract version this engine still serves (see the policy below). | +| `instance_id` | Stable random UUID of this engine, generated once and stored in the data volume (`instance.json`). **Use it as your unique key** for this engine: it survives restarts, upgrades and address changes. It is not derived from the hardware and is not a secret. A wiped data volume creates a new id. | +| `instance_name` | Human-readable name, also the mDNS service name. Defaults to `Smart Frame Engine `; the operator can set `INSTANCE_NAME`. Not guaranteed unique when set by hand: key on `instance_id`. | | `auth` | `open`, `key` or `password`: which credentials the other endpoints need (section 3). | | `capabilities` | Sorted list of feature flags (section 2). | @@ -119,9 +123,12 @@ it needs `network_mode: host`). TXT properties, all strings: | `version` | Same as `/api/health`. | | `api_version` | Same as `/api/health`, as a decimal string. | | `min_api_version` | Same as `/api/health`, as a decimal string. | +| `instance_id` | Same as `/api/health`: match a discovered service to a saved engine with it. | | `path` | `ROOT_PATH` (`/` when served at the root). | | `auth` | `open`, `key` or `password`. | +The service **name** is the engine's `instance_name`, so several engines on one network coexist +(if a name is still taken, the responder renames the service rather than failing). A client can reject an incompatible engine from the record alone. The capability list is **not** in the record (a TXT string is limited to 255 bytes): read it from `GET /api/health` once you have the address and port. @@ -213,6 +220,12 @@ changelog) and run `python scripts/export_openapi.py` (see `CLAUDE.md`). ## Contract Changelog +### 1.1 (engine 1.0.0rc2), additive + +- `GET /api/health` gains `instance_id` and `instance_name`; Zeroconf TXT gains `instance_id` and + the service name becomes the unique `instance_name`, so two engines on one LAN no longer + clash. Clients should use `instance_id` as the stable key of an engine. No `api_version` change. + ### 1.0 (engine 1.0.0rc1) - Initial contract: handshake on `GET /api/health` (`version`, `api_version`, `min_api_version`, diff --git a/docs/openapi.json b/docs/openapi.json index 52efa53..dbd3276 100644 --- a/docs/openapi.json +++ b/docs/openapi.json @@ -1663,6 +1663,16 @@ "title": "Capabilities", "type": "array" }, + "instance_id": { + "description": "Stable random UUID of this engine, generated once and kept in the data volume; use it as the client-side unique key", + "title": "Instance Id", + "type": "string" + }, + "instance_name": { + "description": "Human-readable name (also the mDNS service name)", + "title": "Instance Name", + "type": "string" + }, "min_api_version": { "description": "Oldest contract version still served; a client implementing contract N is compatible when min_api_version <= N <= api_version", "title": "Min Api Version", @@ -1684,6 +1694,8 @@ "version", "api_version", "min_api_version", + "instance_id", + "instance_name", "auth", "capabilities" ], @@ -4051,7 +4063,7 @@ "info": { "description": "\nFetch images from modular sources (Immich, TMDB posters, URLs), optimize them for a\ncolor eInk panel and push them to a Fraimic frame.\n\n**Authentication:** with `ADMIN_PASSWORD` set, every route except `/api/health`, the login\nand the public images needs a web UI session or the API key. With only `APP_API_KEY`, every\n`POST`/`PUT`/`DELETE` route and `/api/config` need the key. Send it as `X-API-Key`,\n`Authorization: Bearer ` or `?api_key=`; use **Authorize** above.\n", "title": "Smart Frame Engine", - "version": "1.0.0rc1" + "version": "1.0.0rc2" }, "openapi": "3.1.0", "paths": { diff --git a/pyproject.toml b/pyproject.toml index 7620af0..41f067d 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta" [project] name = "smart-frame-engine" -version = "1.0.0rc1" +version = "1.0.0rc2" description = "Fetch photos and posters from modular sources, optimize them for color eInk, and push them to a Fraimic frame." readme = "README.md" license = "MIT" diff --git a/tests/test_ambient_family.py b/tests/test_ambient_family.py index 79b33f5..a4fe944 100644 --- a/tests/test_ambient_family.py +++ b/tests/test_ambient_family.py @@ -332,7 +332,7 @@ def __init__(self, fail: bool = False) -> None: self.registered: list[Any] = [] self.closed = False - async def async_register_service(self, info: Any) -> None: + async def async_register_service(self, info: Any, **kwargs: Any) -> None: if self.fail: raise OSError("multicast unavailable") self.registered.append(info) diff --git a/tests/test_api_contract.py b/tests/test_api_contract.py index f5484cd..ea3e4f2 100644 --- a/tests/test_api_contract.py +++ b/tests/test_api_contract.py @@ -2,6 +2,7 @@ from __future__ import annotations +import uuid from importlib.metadata import version as distribution_version import pytest @@ -13,11 +14,14 @@ def test_health_is_the_compatibility_handshake(make_client: ClientFactory) -> None: body = make_client().get("/api/health").json() + assert uuid.UUID(body["instance_id"]) assert body == { "status": "ok", "version": __version__, "api_version": API_VERSION, "min_api_version": MIN_API_VERSION, + "instance_id": body["instance_id"], + "instance_name": body["instance_name"], "auth": "open", "capabilities": capability_names(), } @@ -66,6 +70,13 @@ def test_health_is_listed_in_the_openapi_schema_with_the_handshake_fields( ) -> None: schema = make_client().get("/openapi.json").json() properties = schema["components"]["schemas"]["HealthResponse"]["properties"] - assert {"status", "version", "api_version", "min_api_version", "auth", "capabilities"} <= set( - properties - ) + assert { + "status", + "version", + "api_version", + "min_api_version", + "instance_id", + "instance_name", + "auth", + "capabilities", + } <= set(properties) diff --git a/tests/test_identity.py b/tests/test_identity.py new file mode 100644 index 0000000..8d3bbe2 --- /dev/null +++ b/tests/test_identity.py @@ -0,0 +1,96 @@ +"""Instance identity: stable random id, unique default name, mDNS service naming.""" + +from __future__ import annotations + +import json +import uuid +from pathlib import Path +from typing import Any + +from app.core.identity import DEFAULT_NAME, load_identity +from app.services.discovery import ZeroconfAdvertiser +from tests.conftest import ClientFactory + + +def test_the_id_is_generated_once_and_persisted(tmp_path: Path) -> None: + path = tmp_path / "instance.json" + first = load_identity(path) + assert str(uuid.UUID(first.instance_id)) == first.instance_id + assert json.loads(path.read_text(encoding="utf-8")) == {"instance_id": first.instance_id} + assert load_identity(path) == first # a restart keeps the identity + + +def test_default_name_is_unique_per_instance(tmp_path: Path) -> None: + a = load_identity(tmp_path / "a.json") + b = load_identity(tmp_path / "b.json") + assert a.instance_id != b.instance_id + assert a.instance_name != b.instance_name + assert a.instance_name == f"{DEFAULT_NAME} {a.instance_id[:6]}" + + +def test_name_override_is_trimmed_and_capped(tmp_path: Path) -> None: + named = load_identity(tmp_path / "i.json", " Living room ") + assert named.instance_name == "Living room" + assert len(load_identity(tmp_path / "j.json", "x" * 200).instance_name) == 60 + + +def test_a_corrupt_id_is_replaced(tmp_path: Path) -> None: + path = tmp_path / "instance.json" + path.write_text(json.dumps({"instance_id": "not-a-uuid"}), encoding="utf-8") + identity = load_identity(path) + assert uuid.UUID(identity.instance_id) + assert json.loads(path.read_text(encoding="utf-8"))["instance_id"] == identity.instance_id + + +def test_health_reports_the_persisted_identity(make_client: ClientFactory, data_dir: Path) -> None: + body = make_client().get("/api/health").json() + stored = json.loads((data_dir / "instance.json").read_text(encoding="utf-8")) + assert body["instance_id"] == stored["instance_id"] + assert body["instance_name"].startswith(DEFAULT_NAME) + + +def test_health_uses_the_configured_name(make_client: ClientFactory) -> None: + body = make_client(instance_name="Hallway frame").get("/api/health").json() + assert body["instance_name"] == "Hallway frame" + + +class RecordingZeroconf: + def __init__(self) -> None: + self.registered: list[Any] = [] + self.kwargs: list[dict[str, Any]] = [] + + async def async_register_service(self, info: Any, **kwargs: Any) -> None: + self.registered.append(info) + self.kwargs.append(kwargs) + + async def async_unregister_service(self, info: Any) -> None: + self.registered.remove(info) + + async def async_close(self) -> None: + return None + + +async def test_two_engines_advertise_distinct_service_names() -> None: + zeroconf = RecordingZeroconf() + advertisers = [ + ZeroconfAdvertiser( + port=8080, + version="1", + root_path="", + auth="open", + instance=f"Smart Frame Engine {suffix}", + instance_id=f"id-{suffix}", + zeroconf_factory=lambda: zeroconf, + addresses=lambda: ["192.0.2.10"], + ) + for suffix in ("aaaaaa", "bbbbbb") + ] + for advertiser in advertisers: + assert await advertiser.start() is True + names = {info.name for info in zeroconf.registered} + assert len(names) == 2 + assert {info.decoded_properties["instance_id"] for info in zeroconf.registered} == { + "id-aaaaaa", + "id-bbbbbb", + } + assert all(kwargs == {"allow_name_change": True} for kwargs in zeroconf.kwargs) From f0863b1304256a079002ee9aa4d75adee782e69f Mon Sep 17 00:00:00 2001 From: ant1fr Date: Thu, 19 Nov 2026 14:32:02 +0100 Subject: [PATCH 4/4] fix: stop the worker loops from hanging on shutdown under Python 3.11 The delivery and ephemeral worker loops waited with asyncio.wait_for, which on Python 3.11 can swallow a cancellation (the inner wait and the cancel race). stop() then awaited a loop that never ended, hanging the TestClient teardown (seen in CI as an intermittent Python 3.11 pytest hang, captured by the faulthandler dump). asyncio.timeout does not have that race. Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01VzFCH4ztqBYejkvLvFgnaq --- app/services/delivery.py | 5 ++++- app/services/ephemeral.py | 5 ++++- 2 files changed, 8 insertions(+), 2 deletions(-) diff --git a/app/services/delivery.py b/app/services/delivery.py index d394ec1..adeb8ec 100644 --- a/app/services/delivery.py +++ b/app/services/delivery.py @@ -509,7 +509,10 @@ async def _run(self) -> None: if timeout is None: await self._wake.wait() else: - await asyncio.wait_for(self._wake.wait(), timeout) + # asyncio.timeout, not wait_for: on Python 3.11 wait_for can swallow a + # cancellation, and stop() would then wait for this loop forever. + async with asyncio.timeout(timeout): + await self._wake.wait() except TimeoutError: timed_out = True self._wake.clear() diff --git a/app/services/ephemeral.py b/app/services/ephemeral.py index 842e3cd..cfa6632 100644 --- a/app/services/ephemeral.py +++ b/app/services/ephemeral.py @@ -249,7 +249,10 @@ def _timeout(self) -> float: async def _run(self) -> None: while True: with contextlib.suppress(TimeoutError): - await asyncio.wait_for(self._wake.wait(), self._timeout()) + # asyncio.timeout, not wait_for: on Python 3.11 wait_for can swallow a + # cancellation, and stop() would then wait for this loop forever. + async with asyncio.timeout(self._timeout()): + await self._wake.wait() self._wake.clear() try: await self.expire_if_due()