Skip to content

armgit / sie

Public Imported from GitHub
0

Open-source inference server and production cluster for all the models your agent needs.

27.2 KB
Raw Blame
import asyncio
import logging
import os
import threading
import time
import uuid
from collections.abc import Iterator
from contextlib import contextmanager
from pathlib import Path
from unittest.mock import AsyncMock, MagicMock, patch

import httpx
import pytest
from sie_server.observability import telemetry
from sie_server.observability.telemetry import (
    _CONSECUTIVE_FAILURE_WARN_THRESHOLD,
    _DEFAULT_ON_NOTICE,
    _FIRST_UPDATE_MAX_S,
    _FIRST_UPDATE_MIN_S,
    _UPDATE_MAX_S,
    _UPDATE_MIN_S,
    _build_payload,
    _get_or_create_worker_id,
    _normalize_arch,
    _resolve_telemetry,
    _send_heartbeat,
    _telemetry_loop,
    telemetry_sender,
)


@pytest.fixture(autouse=True)
def _telemetry_env(monkeypatch: pytest.MonkeyPatch) -> None:
    for name in ("SIE_TELEMETRY_ENABLED", "SIE_TELEMETRY_DISABLED", "DO_NOT_TRACK"):
        monkeypatch.delenv(name, raising=False)
    monkeypatch.setattr(telemetry, "_default_on_notice_shown", False)


class TestResolveTelemetry:
    def test_unset_uses_the_release_default(self) -> None:
        assert _resolve_telemetry() == (True, "default")

    @pytest.mark.parametrize("value", ["", "  "])
    def test_empty_uses_the_release_default(self, monkeypatch: pytest.MonkeyPatch, value: str) -> None:
        monkeypatch.setenv("SIE_TELEMETRY_ENABLED", value)
        assert _resolve_telemetry() == (True, "default")

    @pytest.mark.parametrize("value", ["1", "true", "yes", "on", "TRUE", " Yes ", "On"])
    def test_enabled_values_turn_it_on(self, monkeypatch: pytest.MonkeyPatch, value: str) -> None:
        monkeypatch.setenv("SIE_TELEMETRY_ENABLED", value)
        assert _resolve_telemetry() == (True, "SIE_TELEMETRY_ENABLED")

    @pytest.mark.parametrize("value", ["0", "false", "no", "off", "FALSE", " Off "])
    def test_disabled_values_turn_it_off(
        self, monkeypatch: pytest.MonkeyPatch, caplog: pytest.LogCaptureFixture, value: str
    ) -> None:
        monkeypatch.setenv("SIE_TELEMETRY_ENABLED", value)
        with caplog.at_level(logging.WARNING, logger="sie_server.observability.telemetry"):
            assert _resolve_telemetry() == (False, "SIE_TELEMETRY_ENABLED")
        assert caplog.records == []

    @pytest.mark.parametrize("value", ["enable", "maybe", "s3cr3t-value"])
    def test_unrecognised_value_turns_it_off_with_one_warning(
        self, monkeypatch: pytest.MonkeyPatch, caplog: pytest.LogCaptureFixture, value: str
    ) -> None:
        monkeypatch.setenv("SIE_TELEMETRY_ENABLED", value)
        with caplog.at_level(logging.WARNING, logger="sie_server.observability.telemetry"):
            assert _resolve_telemetry() == (False, "SIE_TELEMETRY_ENABLED")
        (record,) = caplog.records
        assert record.levelno == logging.WARNING
        assert "SIE_TELEMETRY_ENABLED has a value that is not recognised" in record.getMessage()
        assert value not in record.getMessage()

    @pytest.mark.parametrize("value", ["disable", "maybe", "s3cr3t-value"])
    @pytest.mark.parametrize("enabled", [None, "1"])
    def test_unrecognised_opt_out_value_turns_it_off_with_one_warning(
        self, monkeypatch: pytest.MonkeyPatch, caplog: pytest.LogCaptureFixture, value: str, enabled: str | None
    ) -> None:
        monkeypatch.setenv("SIE_TELEMETRY_DISABLED", value)
        if enabled is not None:
            monkeypatch.setenv("SIE_TELEMETRY_ENABLED", enabled)
        with caplog.at_level(logging.WARNING, logger="sie_server.observability.telemetry"):
            assert _resolve_telemetry() == (False, "SIE_TELEMETRY_DISABLED")
        (record,) = caplog.records
        assert record.levelno == logging.WARNING
        assert "SIE_TELEMETRY_DISABLED has a value that is not recognised" in record.getMessage()
        assert value not in record.getMessage()

    @pytest.mark.parametrize("value", ["1", "true", "yes", "on", "TRUE", " yes ", "On"])
    @pytest.mark.parametrize("enabled", [None, "1", "on"])
    def test_sie_telemetry_disabled_wins(
        self, monkeypatch: pytest.MonkeyPatch, value: str, enabled: str | None
    ) -> None:
        monkeypatch.setenv("SIE_TELEMETRY_DISABLED", value)
        monkeypatch.setenv("DO_NOT_TRACK", "1")
        if enabled is not None:
            monkeypatch.setenv("SIE_TELEMETRY_ENABLED", enabled)
        assert _resolve_telemetry() == (False, "SIE_TELEMETRY_DISABLED")

    @pytest.mark.parametrize("enabled", [None, "1", "on"])
    def test_do_not_track_wins(self, monkeypatch: pytest.MonkeyPatch, enabled: str | None) -> None:
        monkeypatch.setenv("DO_NOT_TRACK", "1")
        if enabled is not None:
            monkeypatch.setenv("SIE_TELEMETRY_ENABLED", enabled)
        assert _resolve_telemetry() == (False, "DO_NOT_TRACK")

    @pytest.mark.parametrize(
        ("name", "value"),
        [
            ("SIE_TELEMETRY_DISABLED", "0"),
            ("SIE_TELEMETRY_DISABLED", "false"),
            ("SIE_TELEMETRY_DISABLED", "no"),
            ("SIE_TELEMETRY_DISABLED", " Off "),
            ("SIE_TELEMETRY_DISABLED", " "),
            ("DO_NOT_TRACK", "0"),
        ],
    )
    def test_opt_out_variables_set_to_false_do_not_opt_out(
        self, monkeypatch: pytest.MonkeyPatch, caplog: pytest.LogCaptureFixture, name: str, value: str
    ) -> None:
        monkeypatch.setenv(name, value)
        with caplog.at_level(logging.WARNING, logger="sie_server.observability.telemetry"):
            assert _resolve_telemetry() == (True, "default")
        assert caplog.records == []


class TestGetOrCreateWorkerId:
    def test_creates_and_persists_worker_id(self, tmp_path: Path) -> None:
        data_dir = str(tmp_path)
        worker_id = _get_or_create_worker_id(data_dir)
        uuid.UUID(worker_id)  # validates format

        # Second call returns same ID
        worker_id_2 = _get_or_create_worker_id(data_dir)
        assert worker_id == worker_id_2

    def test_corrupt_file_generates_new_id(self, tmp_path: Path) -> None:
        data_dir = str(tmp_path)
        id_path = os.path.join(data_dir, "worker-id")
        with open(id_path, "w") as f:
            f.write("not-a-uuid")

        worker_id = _get_or_create_worker_id(data_dir)
        uuid.UUID(worker_id)  # valid UUID
        assert worker_id != "not-a-uuid"

    @pytest.mark.parametrize("content", ["not-a-uuid", "", "\n"])
    def test_bad_content_is_repaired_once_and_then_stable(self, tmp_path: Path, content: str) -> None:
        id_path = tmp_path / "worker-id"
        id_path.write_text(content)

        repaired = _get_or_create_worker_id(str(tmp_path))

        uuid.UUID(repaired)
        assert id_path.read_text() == repaired
        assert _get_or_create_worker_id(str(tmp_path)) == repaired
        assert [entry.name for entry in tmp_path.iterdir()] == ["worker-id"]

    def test_a_fifo_does_not_block_and_is_replaced(self, tmp_path: Path) -> None:
        id_path = tmp_path / "worker-id"
        os.mkfifo(id_path, 0o600)
        outcome: list[str] = []
        reader = threading.Thread(target=lambda: outcome.append(_get_or_create_worker_id(str(tmp_path))), daemon=True)
        reader.start()
        reader.join(timeout=5)
        try:
            assert not reader.is_alive(), "reading a FIFO worker id blocked"
        finally:
            if reader.is_alive():
                os.close(os.open(id_path, os.O_WRONLY | os.O_NONBLOCK))

        uuid.UUID(outcome[0])
        assert id_path.is_file()
        assert _get_or_create_worker_id(str(tmp_path)) == outcome[0]

    def test_a_fifo_is_never_read_as_the_worker_id(self, tmp_path: Path) -> None:
        id_path = tmp_path / "worker-id"
        os.mkfifo(id_path, 0o600)
        planted = str(uuid.uuid4())
        reader = os.open(id_path, os.O_RDONLY | os.O_NONBLOCK)
        writer = os.open(id_path, os.O_WRONLY)
        try:
            os.write(writer, planted.encode())
            worker_id = _get_or_create_worker_id(str(tmp_path))
        finally:
            os.close(writer)
            os.close(reader)

        assert worker_id != planted
        assert id_path.is_file()
        assert id_path.read_text() == worker_id

    def test_only_old_temporary_files_of_the_server_are_cleaned_up(self, tmp_path: Path) -> None:
        old = time.time() - 600
        orphan = tmp_path / ".worker-id.sie-server-00000000000000aa"
        in_flight = tmp_path / ".worker-id.sie-server-00000000000000bb"
        users = tmp_path / ".worker-id.backup"
        for path in (orphan, in_flight, users):
            path.write_text(str(uuid.uuid4()))
        for path in (orphan, users):
            os.utime(path, (old, old))

        _get_or_create_worker_id(str(tmp_path))

        assert not orphan.exists()
        assert in_flight.exists()
        assert users.exists()

    def test_a_write_interrupted_before_the_rename_is_swept_later(
        self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch
    ) -> None:
        class Interrupted(BaseException):
            pass

        def interrupted(self: Path, target: object) -> Path:
            raise Interrupted

        with monkeypatch.context() as patched:
            patched.setattr(Path, "replace", interrupted)
            with pytest.raises(Interrupted):
                _get_or_create_worker_id(str(tmp_path))
        (leftover,) = tmp_path.iterdir()
        old = time.time() - 600
        os.utime(leftover, (old, old))

        worker_id = _get_or_create_worker_id(str(tmp_path))

        assert not leftover.exists()
        assert [entry.name for entry in tmp_path.iterdir()] == ["worker-id"]
        assert (tmp_path / "worker-id").read_text() == worker_id

    def test_temporary_files_of_another_user_are_kept(self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
        old = time.time() - 600
        orphan = tmp_path / ".worker-id.sie-server-00000000000000aa"
        orphan.write_text(str(uuid.uuid4()))
        os.utime(orphan, (old, old))
        monkeypatch.setattr(os, "getuid", lambda: orphan.stat().st_uid + 1)

        _get_or_create_worker_id(str(tmp_path))

        assert orphan.exists()

    def test_readonly_dir_falls_back_to_ephemeral(self, tmp_path: Path) -> None:
        nonexistent = os.path.join(str(tmp_path), "readonly", "nested", "deep")
        # Make parent read-only
        readonly_parent = Path(str(tmp_path)) / "readonly"
        readonly_parent.mkdir(parents=True)
        readonly_parent.chmod(0o444)

        try:
            worker_id = _get_or_create_worker_id(nonexistent)
            uuid.UUID(worker_id)  # valid UUID, ephemeral
        finally:
            readonly_parent.chmod(0o755)


class TestNormalizeArch:
    def test_x86_64_to_amd64(self) -> None:
        assert _normalize_arch("x86_64") == "amd64"

    def test_amd64_passthrough(self) -> None:
        assert _normalize_arch("amd64") == "amd64"

    def test_aarch64_to_arm64(self) -> None:
        assert _normalize_arch("aarch64") == "arm64"

    def test_arm64_passthrough(self) -> None:
        assert _normalize_arch("arm64") == "arm64"

    def test_unknown_arch_lowered(self) -> None:
        assert _normalize_arch("MIPS") == "mips"


class TestBuildPayload:
    def test_all_fields_present(self, monkeypatch: pytest.MonkeyPatch) -> None:
        monkeypatch.delenv("SIE_VARIANT", raising=False)
        monkeypatch.delenv("SIE_DEPLOYMENT_ENV", raising=False)

        payload = _build_payload("test-worker-id", "init", ["NVIDIA L4"])

        assert payload["worker_id"] == "test-worker-id"
        assert payload["event"] == "init"
        assert payload["sie_version"] is not None
        assert payload["variant"] is None
        assert payload["os"] is not None
        assert payload["arch"] in ("amd64", "arm64") or isinstance(payload["arch"], str)
        assert payload["gpus"] == ["NVIDIA L4"]
        assert payload["deployment_env"] == "unknown"
        assert "sent_at" in payload

    def test_deployment_env_defaults_to_unknown(self, monkeypatch: pytest.MonkeyPatch) -> None:
        monkeypatch.delenv("SIE_DEPLOYMENT_ENV", raising=False)
        payload = _build_payload("w", "init", [])
        assert payload["deployment_env"] == "unknown"

    def test_deployment_env_from_env_var(self, monkeypatch: pytest.MonkeyPatch) -> None:
        monkeypatch.setenv("SIE_DEPLOYMENT_ENV", "staging")
        payload = _build_payload("w", "init", [])
        assert payload["deployment_env"] == "staging"

    def test_variant_from_env_var(self, monkeypatch: pytest.MonkeyPatch) -> None:
        monkeypatch.setenv("SIE_VARIANT", "cuda12-default")
        payload = _build_payload("w", "init", [])
        assert payload["variant"] == "cuda12-default"

    def test_gpu_names_list(self) -> None:
        payload = _build_payload("w", "update", ["NVIDIA L4", "NVIDIA A100"])
        assert payload["gpus"] == ["NVIDIA L4", "NVIDIA A100"]

    def test_empty_gpus(self) -> None:
        payload = _build_payload("w", "update", [])
        assert payload["gpus"] == []


class TestSendHeartbeat:
    @pytest.mark.asyncio
    async def test_success_returns_true(self) -> None:
        mock_response = MagicMock()
        mock_response.is_success = True
        client = AsyncMock(spec=httpx.AsyncClient)
        client.post.return_value = mock_response

        result = await _send_heartbeat(client, "http://test.example.com", {"event": "init"})
        assert result is True
        client.post.assert_called_once()

    @pytest.mark.asyncio
    async def test_failure_returns_false(self) -> None:
        mock_response = MagicMock()
        mock_response.is_success = False
        client = AsyncMock(spec=httpx.AsyncClient)
        client.post.return_value = mock_response

        result = await _send_heartbeat(client, "http://test.example.com", {"event": "init"})
        assert result is False

    @pytest.mark.asyncio
    async def test_exception_returns_false(self) -> None:
        client = AsyncMock(spec=httpx.AsyncClient)
        client.post.side_effect = httpx.ConnectError("connection refused")

        result = await _send_heartbeat(client, "http://test.example.com", {"event": "init"})
        assert result is False


class TestTelemetryLoop:
    @pytest.mark.asyncio
    async def test_sends_init_then_stops(self) -> None:
        mock_response = MagicMock()
        mock_response.is_success = True
        client = AsyncMock(spec=httpx.AsyncClient)
        client.post.return_value = mock_response

        stop_event = asyncio.Event()
        # Set stop immediately so the loop exits after INIT
        stop_event.set()

        await _telemetry_loop(client, "http://test.example.com", "worker-1", ["NVIDIA L4"], stop_event)

        # Should have sent at least the INIT event
        assert client.post.call_count >= 1
        first_call_payload = client.post.call_args_list[0].kwargs.get("json") or client.post.call_args_list[0][1].get(
            "json"
        )
        assert first_call_payload["event"] == "init"

    @pytest.mark.asyncio
    async def test_failure_counter_warns_after_threshold(self, caplog: pytest.LogCaptureFixture) -> None:
        mock_response = MagicMock()
        mock_response.is_success = False
        client = AsyncMock(spec=httpx.AsyncClient)
        client.post.return_value = mock_response

        stop_event = asyncio.Event()

        # Patch random.uniform to return 0 so the loop progresses instantly
        with patch("sie_server.observability.telemetry.random.uniform", return_value=0.0):
            # Run the loop for a short time then stop
            async def stop_after_sends() -> None:
                # Wait until enough failures have occurred
                while client.post.call_count < _CONSECUTIVE_FAILURE_WARN_THRESHOLD + 2:  # noqa: ASYNC110
                    await asyncio.sleep(0.01)
                stop_event.set()

            task = asyncio.create_task(stop_after_sends())
            await _telemetry_loop(client, "http://test.example.com", "worker-1", [], stop_event)
            await task

        assert any("consecutive send failures" in r.message for r in caplog.records)

    @pytest.mark.asyncio
    async def test_success_resets_failure_counter(self) -> None:
        call_count = 0

        mock_success = MagicMock()
        mock_success.is_success = True
        mock_failure = MagicMock()
        mock_failure.is_success = False

        client = AsyncMock(spec=httpx.AsyncClient)

        def side_effect(*args, **kwargs):
            nonlocal call_count
            call_count += 1
            # First call (INIT) succeeds, next 2 fail, then succeed
            if call_count == 1 or call_count >= 4:
                return mock_success
            return mock_failure

        client.post.side_effect = side_effect

        stop_event = asyncio.Event()

        with patch("sie_server.observability.telemetry.random.uniform", return_value=0.0):

            async def stop_after_sends() -> None:
                while client.post.call_count < 5:  # noqa: ASYNC110
                    await asyncio.sleep(0.01)
                stop_event.set()

            task = asyncio.create_task(stop_after_sends())
            await _telemetry_loop(client, "http://test.example.com", "worker-1", [], stop_event)
            await task

        # No warning should have been logged since counter was reset before reaching threshold


class TestJitterRanges:
    def test_first_update_range(self) -> None:
        assert _FIRST_UPDATE_MIN_S == 45 * 60
        assert _FIRST_UPDATE_MAX_S == 75 * 60

    def test_update_range(self) -> None:
        assert _UPDATE_MIN_S == 55 * 60
        assert _UPDATE_MAX_S == 65 * 60


@contextmanager
def _receiver() -> Iterator[MagicMock]:
    with (
        patch("sie_server.observability.telemetry.httpx.AsyncClient") as mock_client_cls,
        patch("sie_server.observability.telemetry.get_gpu_metrics", return_value=[]),
    ):
        mock_client = AsyncMock()
        mock_client.post = AsyncMock(return_value=MagicMock(is_success=True))
        mock_client.aclose = AsyncMock()
        mock_client_cls.return_value = mock_client
        yield mock_client_cls


def _telemetry_messages(caplog: pytest.LogCaptureFixture, level: int) -> list[str]:
    return [
        r.getMessage() for r in caplog.records if r.name == "sie_server.observability.telemetry" and r.levelno == level
    ]


class TestTelemetrySender:
    @pytest.mark.asyncio
    @pytest.mark.parametrize(
        ("name", "value", "source"),
        [
            ("SIE_TELEMETRY_DISABLED", "1", "SIE_TELEMETRY_DISABLED"),
            ("SIE_TELEMETRY_DISABLED", "maybe", "SIE_TELEMETRY_DISABLED"),
            ("DO_NOT_TRACK", "1", "DO_NOT_TRACK"),
            ("SIE_TELEMETRY_ENABLED", "0", "SIE_TELEMETRY_ENABLED"),
            ("SIE_TELEMETRY_ENABLED", "maybe", "SIE_TELEMETRY_ENABLED"),
        ],
    )
    async def test_off_states_its_source_and_sends_nothing(
        self, monkeypatch: pytest.MonkeyPatch, caplog: pytest.LogCaptureFixture, name: str, value: str, source: str
    ) -> None:
        monkeypatch.setenv(name, value)
        with _receiver() as mock_client_cls, caplog.at_level(logging.INFO):
            async with telemetry_sender():
                pass
        assert _telemetry_messages(caplog, logging.INFO) == [f"telemetry: off ({source})"]
        assert _DEFAULT_ON_NOTICE not in _telemetry_messages(caplog, logging.WARNING)
        mock_client_cls.assert_not_called()

    @pytest.mark.asyncio
    @pytest.mark.parametrize("value", ["1", "true", "yes", "on"])
    async def test_explicit_opt_in_states_its_source_without_the_notice(
        self, monkeypatch: pytest.MonkeyPatch, caplog: pytest.LogCaptureFixture, tmp_path: Path, value: str
    ) -> None:
        monkeypatch.setenv("SIE_DATA_DIR", str(tmp_path))
        monkeypatch.setenv("SIE_TELEMETRY_ENABLED", value)
        with _receiver() as mock_client_cls, caplog.at_level(logging.INFO):
            async with telemetry_sender():
                pass
        assert _telemetry_messages(caplog, logging.INFO) == ["telemetry: on (SIE_TELEMETRY_ENABLED)"]
        assert _telemetry_messages(caplog, logging.WARNING) == []
        mock_client_cls.assert_called_once()

    @pytest.mark.asyncio
    async def test_default_on_states_its_source_every_start_and_warns_once(
        self, monkeypatch: pytest.MonkeyPatch, caplog: pytest.LogCaptureFixture, tmp_path: Path
    ) -> None:
        monkeypatch.setenv("SIE_DATA_DIR", str(tmp_path))
        with _receiver(), caplog.at_level(logging.INFO):
            for _ in range(2):
                async with telemetry_sender():
                    pass
        assert _telemetry_messages(caplog, logging.INFO) == ["telemetry: on (default)"] * 2
        assert _telemetry_messages(caplog, logging.WARNING) == [_DEFAULT_ON_NOTICE]

    def test_default_on_notice_names_the_flip_release_and_both_variables(self) -> None:
        assert "From 0.13.0 it is off unless SIE_TELEMETRY_ENABLED=1." in _DEFAULT_ON_NOTICE
        assert "SIE_TELEMETRY_DISABLED=1 to stop now" in _DEFAULT_ON_NOTICE
        assert "https://github.com/superlinked/sie#telemetry" in _DEFAULT_ON_NOTICE

    @pytest.mark.asyncio
    async def test_lifecycle_init_terminate(self, monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> None:
        monkeypatch.delenv("SIE_TELEMETRY_DISABLED", raising=False)
        monkeypatch.delenv("DO_NOT_TRACK", raising=False)
        monkeypatch.setenv("SIE_DATA_DIR", str(tmp_path))

        sent_payloads: list[dict] = []

        mock_response = MagicMock()
        mock_response.is_success = True

        async def capture_post(*args, **kwargs):
            payload = kwargs.get("json", {})
            sent_payloads.append(payload)
            return mock_response

        with (
            patch("sie_server.observability.telemetry.httpx.AsyncClient") as mock_client_cls,
            patch("sie_server.observability.telemetry.get_gpu_metrics", return_value=[]),
        ):
            mock_client = AsyncMock()
            mock_client.post = AsyncMock(side_effect=capture_post)
            mock_client.aclose = AsyncMock()
            mock_client_cls.return_value = mock_client

            async with telemetry_sender():
                # Give the background task a moment to send INIT
                await asyncio.sleep(0.1)

        # Should have INIT and TERMINATE events
        events = [p.get("event") for p in sent_payloads]
        assert "init" in events
        assert "terminate" in events

    @pytest.mark.asyncio
    async def test_terminate_timeout_does_not_block(self, monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> None:
        monkeypatch.delenv("SIE_TELEMETRY_DISABLED", raising=False)
        monkeypatch.delenv("DO_NOT_TRACK", raising=False)
        monkeypatch.setenv("SIE_DATA_DIR", str(tmp_path))

        async def slow_post(*args, **kwargs):
            await asyncio.sleep(100)  # simulate unreachable receiver
            return MagicMock(is_success=True)

        with (
            patch("sie_server.observability.telemetry.httpx.AsyncClient") as mock_client_cls,
            patch("sie_server.observability.telemetry.get_gpu_metrics", return_value=[]),
            patch("sie_server.observability.telemetry._SEND_TIMEOUT_S", 0.1),
        ):
            mock_client = AsyncMock()
            mock_client.post = AsyncMock(side_effect=slow_post)
            mock_client.aclose = AsyncMock()
            mock_client_cls.return_value = mock_client

            # Should not hang
            async with telemetry_sender():
                await asyncio.sleep(0.05)

    @pytest.mark.asyncio
    async def test_endpoint_override(self, monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> None:
        monkeypatch.delenv("SIE_TELEMETRY_DISABLED", raising=False)
        monkeypatch.delenv("DO_NOT_TRACK", raising=False)
        monkeypatch.setenv("SIE_DATA_DIR", str(tmp_path))
        custom_url = "https://custom.example.com/telemetry"
        monkeypatch.setenv("SIE_TELEMETRY_URL", custom_url)

        called_urls: list[str] = []
        mock_response = MagicMock()
        mock_response.is_success = True

        async def capture_post(url, *args, **kwargs):
            called_urls.append(url)
            return mock_response

        with (
            patch("sie_server.observability.telemetry.httpx.AsyncClient") as mock_client_cls,
            patch("sie_server.observability.telemetry.get_gpu_metrics", return_value=[]),
        ):
            mock_client = AsyncMock()
            mock_client.post = AsyncMock(side_effect=capture_post)
            mock_client.aclose = AsyncMock()
            mock_client_cls.return_value = mock_client

            async with telemetry_sender():
                await asyncio.sleep(0.1)

        assert all(url == custom_url for url in called_urls)

    @pytest.mark.asyncio
    async def test_gpu_names_extraction(self, monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> None:
        monkeypatch.delenv("SIE_TELEMETRY_DISABLED", raising=False)
        monkeypatch.delenv("DO_NOT_TRACK", raising=False)
        monkeypatch.setenv("SIE_DATA_DIR", str(tmp_path))

        gpu_data = [
            {
                "device": "cuda:0",
                "name": "NVIDIA L4",
                "gpu_type": "l4",
                "utilization_pct": 50,
                "memory_used_bytes": 0,
                "memory_total_bytes": 0,
            },
            {
                "device": "cuda:1",
                "name": "NVIDIA A100",
                "gpu_type": "a100-40gb",
                "utilization_pct": 60,
                "memory_used_bytes": 0,
                "memory_total_bytes": 0,
            },
        ]

        sent_payloads: list[dict] = []
        mock_response = MagicMock()
        mock_response.is_success = True

        async def capture_post(*args, **kwargs):
            sent_payloads.append(kwargs.get("json", {}))
            return mock_response

        with (
            patch("sie_server.observability.telemetry.httpx.AsyncClient") as mock_client_cls,
            patch("sie_server.observability.telemetry.get_gpu_metrics", return_value=gpu_data),
        ):
            mock_client = AsyncMock()
            mock_client.post = AsyncMock(side_effect=capture_post)
            mock_client.aclose = AsyncMock()
            mock_client_cls.return_value = mock_client

            async with telemetry_sender():
                await asyncio.sleep(0.1)

        init_payloads = [p for p in sent_payloads if p.get("event") == "init"]
        assert len(init_payloads) >= 1
        assert init_payloads[0]["gpus"] == ["NVIDIA L4", "NVIDIA A100"]

    @pytest.mark.asyncio
    async def test_gpu_detection_failure_gives_empty_list(
        self, monkeypatch: pytest.MonkeyPatch, tmp_path: Path
    ) -> None:
        monkeypatch.delenv("SIE_TELEMETRY_DISABLED", raising=False)
        monkeypatch.delenv("DO_NOT_TRACK", raising=False)
        monkeypatch.setenv("SIE_DATA_DIR", str(tmp_path))

        sent_payloads: list[dict] = []
        mock_response = MagicMock()
        mock_response.is_success = True

        async def capture_post(*args, **kwargs):
            sent_payloads.append(kwargs.get("json", {}))
            return mock_response

        with (
            patch("sie_server.observability.telemetry.httpx.AsyncClient") as mock_client_cls,
            patch("sie_server.observability.telemetry.get_gpu_metrics", side_effect=RuntimeError("NVML failed")),
        ):
            mock_client = AsyncMock()
            mock_client.post = AsyncMock(side_effect=capture_post)
            mock_client.aclose = AsyncMock()
            mock_client_cls.return_value = mock_client

            async with telemetry_sender():
                await asyncio.sleep(0.1)

        init_payloads = [p for p in sent_payloads if p.get("event") == "init"]
        assert len(init_payloads) >= 1
        assert init_payloads[0]["gpus"] == []