From 2cbfffe10df4c9a50f952dea8fb495c72304f40c Mon Sep 17 00:00:00 2001 From: Marc Duiker <4191277+marcduiker@users.noreply.github.com> Date: Tue, 17 Nov 2026 11:19:27 +0100 Subject: [PATCH 1/9] refactor(analytics): send usage events through a destination list Co-Authored-By: Claude Opus 5.5 Signed-off-by: Marc Duiker <4191277+marcduiker@users.noreply.github.com> --- diagrid/agent/core/workflow/runner.py | 4 +- diagrid/core/analytics.py | 141 ++++++++++++++----- tests/core/test_analytics.py | 194 ++++++++++++++++++++++++++ 3 files changed, 299 insertions(+), 40 deletions(-) diff --git a/diagrid/agent/core/workflow/runner.py b/diagrid/agent/core/workflow/runner.py index 0a29dd46..d5df690a 100644 --- a/diagrid/agent/core/workflow/runner.py +++ b/diagrid/agent/core/workflow/runner.py @@ -26,8 +26,8 @@ try: from diagrid.core.analytics import report_usage except ImportError: # pragma: no cover - older diagrid-core - - def report_usage(package: str, **dimensions: object) -> None: + # The fallback has no ``sinks`` parameter: an older core has no destination list. + def report_usage(package: str, **dimensions: object) -> None: # type: ignore[misc] return None diff --git a/diagrid/core/analytics.py b/diagrid/core/analytics.py index 51577fb4..56fddbb4 100644 --- a/diagrid/core/analytics.py +++ b/diagrid/core/analytics.py @@ -18,7 +18,8 @@ blackholes lookups. The calling thread never waits on it. Blocked egress and air-gapped clusters are normal conditions, not faults. -Set ``USAGE_ENDPOINT`` to an empty string to turn the module into a no-op. +Events go to every destination in ``USAGE_SINKS``. Set ``USAGE_ENDPOINT`` to an +empty string to turn the Scarf destination into a no-op. """ from __future__ import annotations @@ -29,7 +30,10 @@ import threading import urllib.parse import urllib.request +from collections.abc import Callable, Mapping, Sequence +from dataclasses import dataclass from importlib import metadata +from typing import Any logger = logging.getLogger(__name__) @@ -64,7 +68,7 @@ _DIMENSION_MAX_LEN = 64 _reported_lock = threading.Lock() -_reported_packages: set[str] = set() +_reported_packages: set[tuple[str, str]] = set() def _is_truthy(value: str) -> bool: @@ -116,14 +120,9 @@ def _clean_dimension(value: object) -> str: return str(value).strip()[:_DIMENSION_MAX_LEN] -def build_url(package: str, version: str, **dimensions: object) -> str: - """Build the event URL for ``package``. Exposed for tests. - - The defaults describe the package and the host. ``dimensions`` are added by - the caller (for example ``kind`` and ``framework``) and override a default - of the same name. Empty values are dropped. - """ - params: dict[str, str] = { +def _default_dimensions(package: str, version: str) -> dict[str, str]: + """Return the dimensions every destination reports: the package and the host.""" + return { "package": package, "version": version, "core_version": package_version("diagrid-core"), @@ -133,6 +132,16 @@ def build_url(package: str, version: str, **dimensions: object) -> str: "target": detect_target(), "ci": "true" if running_in_ci() else "false", } + + +def build_url(package: str, version: str, **dimensions: object) -> str: + """Build the Scarf event URL for ``package``. Exposed for tests. + + The defaults describe the package and the host. ``dimensions`` are added by + the caller (for example ``kind`` and ``framework``) and override a default + of the same name. Empty values are dropped. + """ + params = _default_dimensions(package, version) for key, value in dimensions.items(): if value is None: continue @@ -142,47 +151,103 @@ def build_url(package: str, version: str, **dimensions: object) -> str: return f"{USAGE_ENDPOINT}?{urllib.parse.urlencode(params)}" -def _send_event(package: str, dimensions: dict[str, object]) -> None: - """Send one event and swallow every failure.""" - try: - version = package_version(package) - request = urllib.request.Request( - build_url(package, version, **dimensions), - headers={"User-Agent": f"{package}/{version}"}, - ) - with urllib.request.urlopen(request, timeout=USAGE_TIMEOUT_SECONDS): - pass - logger.debug("usage event sent for %s %s", package, version) - except Exception as exc: - logger.debug("usage event for %s not sent: %r", package, exc) +def _always() -> bool: + return True -def report_usage(package: str, **dimensions: object) -> None: - """Report one usage event per package per process, on a daemon thread. +@dataclass(frozen=True) +class Sink: + """One usage-analytics destination. + + ``allowed`` is that destination's gate, evaluated on the calling thread + before anything is sent. ``build_request`` turns a package and the caller's + dimensions into the request to send. ``configured`` is False while the + destination has no endpoint, which makes it a no-op that is not even counted + as reported. + """ + + name: str + allowed: Callable[[], bool] + build_request: Callable[[str, Mapping[str, Any]], urllib.request.Request] + configured: Callable[[], bool] = _always + + +def _scarf_request( + package: str, dimensions: Mapping[str, Any] +) -> urllib.request.Request: + version = package_version(package) + return urllib.request.Request( + build_url(package, version, **dimensions), + headers={"User-Agent": f"{package}/{version}"}, + ) + + +SCARF_SINK = Sink( + name="scarf", + allowed=lambda: not usage_reporting_disabled(), + build_request=_scarf_request, + configured=lambda: bool(USAGE_ENDPOINT), +) + +USAGE_SINKS: tuple[Sink, ...] = (SCARF_SINK,) + + +def _send_event( + package: str, + dimensions: dict[str, object], + sinks: Sequence[Sink] = USAGE_SINKS, +) -> None: + """Send one event to each sink and swallow every failure.""" + for sink in sinks: + try: + request = sink.build_request(package, dimensions) + with urllib.request.urlopen(request, timeout=USAGE_TIMEOUT_SECONDS): + pass + logger.debug("usage event sent for %s to %s", package, sink.name) + except Exception as exc: + logger.debug( + "usage event for %s not sent to %s: %r", package, sink.name, exc + ) + + +def report_usage( + package: str, *, sinks: Sequence[Sink] = USAGE_SINKS, **dimensions: object +) -> None: + """Report one usage event per package per sink per process, on a daemon thread. ``package`` is the distribution that triggered the call, for example ``diagrid`` for an agent runner. ``dimensions`` are extra query parameters such as ``kind`` and ``framework``. Never blocks the caller and never - raises. Does nothing while ``USAGE_ENDPOINT`` is empty or when the user - opted out. + raises. A sink is skipped while it has no endpoint or when its gate is + closed, for example when the user opted out. """ try: - if not USAGE_ENDPOINT: - return - with _reported_lock: - if package in _reported_packages: - return - _reported_packages.add(package) - - if usage_reporting_disabled(): - logger.debug( - "usage reporting for %s is disabled by the environment", package - ) + selected: list[Sink] = [] + for sink in sinks: + try: + if not sink.configured(): + continue + key = (sink.name, package) + with _reported_lock: + if key in _reported_packages: + continue + _reported_packages.add(key) + + if not sink.allowed(): + logger.debug( + "usage reporting for %s to %s is disabled", package, sink.name + ) + continue + selected.append(sink) + except Exception: + continue + if not selected: return thread = threading.Thread( target=_send_event, args=(package, dict(dimensions)), + kwargs={"sinks": tuple(selected)}, name="diagrid-usage", daemon=True, ) diff --git a/tests/core/test_analytics.py b/tests/core/test_analytics.py index 0b7e6768..bd412d83 100644 --- a/tests/core/test_analytics.py +++ b/tests/core/test_analytics.py @@ -5,6 +5,10 @@ from __future__ import annotations +import urllib.parse +import urllib.request +from collections.abc import Callable +from typing import Any, NamedTuple from unittest.mock import patch import pytest @@ -34,6 +38,98 @@ def _clean_state(monkeypatch: pytest.MonkeyPatch) -> None: monkeypatch.delenv(name, raising=False) +class Recorded(NamedTuple): + url: str + sink: str + package: str + + +class _SyncThread: + """Runs the target inline on ``start``, so tests never sleep or join.""" + + def __init__( + self, + target: Callable[..., Any], + args: Any = (), + kwargs: Any = None, + **_: Any, + ) -> None: + self._target = target + self._args = args + self._kwargs = kwargs or {} + + def start(self) -> None: + self._target(*self._args, **self._kwargs) + + +class _Response: + def __enter__(self) -> "_Response": + return self + + def __exit__(self, *_: Any) -> None: + return None + + +def record_requests(monkeypatch: pytest.MonkeyPatch) -> list[Recorded]: + """Make sends synchronous and record each request instead of sending it. + + A recorded request carries the sink name from the ``X-Test-Sink`` header + (empty for the real Scarf sink) and the ``package`` query parameter. + """ + recorded: list[Recorded] = [] + + def fake_urlopen(request: Any, timeout: float = 0) -> _Response: + query = urllib.parse.parse_qs(urllib.parse.urlsplit(request.full_url).query) + recorded.append( + Recorded( + request.full_url, + request.get_header("X-test-sink") or "", + query.get("package", [""])[0], + ) + ) + return _Response() + + monkeypatch.setattr(analytics.urllib.request, "urlopen", fake_urlopen) + monkeypatch.setattr(analytics.threading, "Thread", _SyncThread) + return recorded + + +def clear_opt_out(monkeypatch: pytest.MonkeyPatch) -> None: + for name in analytics.OPT_OUT_ENV_VARS: + monkeypatch.delenv(name, raising=False) + + +def test_scarf_url_is_the_documented_shape(monkeypatch: pytest.MonkeyPatch) -> None: + monkeypatch.setattr( + analytics, "USAGE_ENDPOINT", "https://diagrid.gateway.scarf.sh/python-ai" + ) + recorded = record_requests(monkeypatch) + clear_opt_out(monkeypatch) + # ``version`` is the installed version of the package, so pin it. Every + # host-derived default is overridden, so the URL is the same on every + # machine, OS and Python version. + monkeypatch.setattr(analytics, "package_version", lambda _package: "0.5.3") + analytics.report_usage( + "diagrid", + core_version="0.5.3", + os="linux", + arch="x86_64", + python_version="3.12.1", + target="dapr", + ci="false", + kind="workflow", + framework="langgraph", + framework_version="0.2.0", + ) + assert len(recorded) == 1 + assert recorded[0].url == ( + "https://diagrid.gateway.scarf.sh/python-ai" + "?package=diagrid&version=0.5.3&core_version=0.5.3&os=linux&arch=x86_64" + "&python_version=3.12.1&target=dapr&ci=false&kind=workflow" + "&framework=langgraph&framework_version=0.2.0" + ) + + def test_does_nothing_while_endpoint_is_empty(monkeypatch: pytest.MonkeyPatch) -> None: monkeypatch.setattr(analytics, "USAGE_ENDPOINT", "") with patch.object(analytics.threading, "Thread") as thread: @@ -221,3 +317,101 @@ def test_target_detection( def test_unknown_package_version_does_not_raise() -> None: assert analytics.package_version("diagrid-does-not-exist") == "unknown" + + +def _fake_sink( + name: str, + *, + allowed: Callable[[], bool] = lambda: True, + raises: bool = False, +) -> analytics.Sink: + def build_request(package: str, dimensions: Any) -> urllib.request.Request: + if raises: + raise RuntimeError("boom") + return urllib.request.Request( + f"https://example.invalid/{name}?package={package}", + headers={"X-Test-Sink": name}, + ) + + return analytics.Sink(name=name, allowed=allowed, build_request=build_request) + + +def sink_recording_as(name: str) -> analytics.Sink: + return _fake_sink(name) + + +def sink_never_allowed_as(name: str) -> analytics.Sink: + return _fake_sink(name, allowed=lambda: False) + + +def sink_that_raises_as(name: str) -> analytics.Sink: + return _fake_sink(name, raises=True) + + +def test_report_usage_sends_to_each_allowed_sink( + monkeypatch: pytest.MonkeyPatch, +) -> None: + recorded = record_requests(monkeypatch) + sinks = (sink_recording_as("a"), sink_recording_as("b")) + analytics.report_usage("diagrid", sinks=sinks) + assert {r.sink for r in recorded} == {"a", "b"} + + +def test_report_usage_skips_a_sink_whose_gate_is_closed( + monkeypatch: pytest.MonkeyPatch, +) -> None: + recorded = record_requests(monkeypatch) + sinks = (sink_recording_as("a"), sink_never_allowed_as("b")) + analytics.report_usage("diagrid", sinks=sinks) + assert {r.sink for r in recorded} == {"a"} + + +def test_dedupe_is_per_sink_per_package(monkeypatch: pytest.MonkeyPatch) -> None: + # One event per package per process, per destination. A closed gate on one + # sink must not consume the other sink's single send. + recorded = record_requests(monkeypatch) + sinks = (sink_recording_as("a"), sink_recording_as("b")) + analytics.report_usage("diagrid", sinks=sinks) + analytics.report_usage("diagrid", sinks=sinks) + analytics.report_usage("diagrid-cli", sinks=sinks) + assert sorted((r.sink, r.package) for r in recorded) == [ + ("a", "diagrid"), + ("a", "diagrid-cli"), + ("b", "diagrid"), + ("b", "diagrid-cli"), + ] + + +def test_a_closed_gate_does_not_consume_another_sinks_send( + monkeypatch: pytest.MonkeyPatch, +) -> None: + recorded = record_requests(monkeypatch) + analytics.report_usage("diagrid", sinks=(sink_never_allowed_as("a"),)) + analytics.report_usage("diagrid", sinks=(sink_recording_as("b"),)) + assert [(r.sink, r.package) for r in recorded] == [("b", "diagrid")] + + +def test_a_raising_sink_does_not_stop_the_others( + monkeypatch: pytest.MonkeyPatch, +) -> None: + recorded = record_requests(monkeypatch) + sinks = (sink_that_raises_as("a"), sink_recording_as("b")) + analytics.report_usage("diagrid", sinks=sinks) + assert {r.sink for r in recorded} == {"b"} + + +def test_a_sink_whose_gate_raises_does_not_stop_the_others( + monkeypatch: pytest.MonkeyPatch, +) -> None: + def explode() -> bool: + raise RuntimeError("boom") + + recorded = record_requests(monkeypatch) + sinks = (_fake_sink("a", allowed=explode), sink_recording_as("b")) + analytics.report_usage("diagrid", sinks=sinks) + assert {r.sink for r in recorded} == {"b"} + + +def test_scarf_is_the_default_destination() -> None: + assert analytics.USAGE_SINKS == (analytics.SCARF_SINK,) + assert analytics.SCARF_SINK.name == "scarf" From 25caff237f2460c93ccfabb9338f8157673de73e Mon Sep 17 00:00:00 2001 From: Marc Duiker <4191277+marcduiker@users.noreply.github.com> Date: Tue, 17 Nov 2026 11:22:49 +0100 Subject: [PATCH 2/9] feat(analytics): gate Reo events on cluster, target and CI Co-Authored-By: Claude Opus 5.5 Signed-off-by: Marc Duiker <4191277+marcduiker@users.noreply.github.com> --- diagrid/core/analytics.py | 20 ++++++++ tests/core/test_analytics.py | 96 ++++++++++++++++++++++++++++++++++++ 2 files changed, 116 insertions(+) diff --git a/diagrid/core/analytics.py b/diagrid/core/analytics.py index 56fddbb4..13269e60 100644 --- a/diagrid/core/analytics.py +++ b/diagrid/core/analytics.py @@ -192,6 +192,26 @@ def _scarf_request( USAGE_SINKS: tuple[Sink, ...] = (SCARF_SINK,) +def reo_allowed() -> bool: + """Return True when a Reo event may be sent. Fails closed. + + Stricter than Scarf's gate. All of these must hold: no opt-out variable is + set, the process is not inside a Kubernetes cluster (no exceptions), it is + not pointed at Catalyst, and it is not running in CI. Anything that cannot + be determined, including an exception, means no event. + """ + try: + if usage_reporting_disabled(): + return False + if "KUBERNETES_SERVICE_HOST" in os.environ: + return False + if detect_target() != "dapr": + return False + return not running_in_ci() + except Exception: + return False + + def _send_event( package: str, dimensions: dict[str, object], diff --git a/tests/core/test_analytics.py b/tests/core/test_analytics.py index bd412d83..a3a13a84 100644 --- a/tests/core/test_analytics.py +++ b/tests/core/test_analytics.py @@ -415,3 +415,99 @@ def explode() -> bool: def test_scarf_is_the_default_destination() -> None: assert analytics.USAGE_SINKS == (analytics.SCARF_SINK,) assert analytics.SCARF_SINK.name == "scarf" + + +def clear_all_gate_vars(monkeypatch: pytest.MonkeyPatch) -> None: + """Clear every variable the Reo gate reads, so a gate-open test is not vacuous.""" + for name in (*_ENV_TO_CLEAR, "KUBERNETES_SERVICE_HOST"): + monkeypatch.delenv(name, raising=False) + + +def test_reo_gate_open_on_a_clean_developer_machine( + monkeypatch: pytest.MonkeyPatch, +) -> None: + clear_all_gate_vars(monkeypatch) + assert analytics.reo_allowed() is True + + +@pytest.mark.parametrize( + "var", ["DO_NOT_TRACK", "SCARF_NO_ANALYTICS", "DIAGRID_NO_ANALYTICS"] +) +def test_reo_gate_closed_on_opt_out(monkeypatch: pytest.MonkeyPatch, var: str) -> None: + clear_all_gate_vars(monkeypatch) + monkeypatch.setenv(var, "1") + assert analytics.reo_allowed() is False + + +def test_reo_gate_closed_in_kubernetes(monkeypatch: pytest.MonkeyPatch) -> None: + clear_all_gate_vars(monkeypatch) + monkeypatch.setenv("KUBERNETES_SERVICE_HOST", "10.0.0.1") + assert analytics.reo_allowed() is False + + +@pytest.mark.parametrize( + "var,value", + [ + ("DAPR_API_TOKEN", "t"), + ("DAPR_GRPC_ENDPOINT", "https://grpc.abc.diagrid.io:443"), + ("DAPR_HTTP_ENDPOINT", "https://http.abc.diagrid.io"), + ], +) +def test_reo_gate_closed_when_pointed_at_catalyst( + monkeypatch: pytest.MonkeyPatch, var: str, value: str +) -> None: + clear_all_gate_vars(monkeypatch) + monkeypatch.setenv(var, value) + assert analytics.reo_allowed() is False + + +@pytest.mark.parametrize( + "var", + [ + "CI", + "GITHUB_ACTIONS", + "GITLAB_CI", + "CIRCLECI", + "TRAVIS", + "TF_BUILD", + "BUILDKITE", + "JENKINS_URL", + ], +) +def test_reo_gate_closed_in_ci(monkeypatch: pytest.MonkeyPatch, var: str) -> None: + clear_all_gate_vars(monkeypatch) + monkeypatch.setenv(var, "true") + assert analytics.reo_allowed() is False + + +def test_reo_gate_fails_closed_on_malformed_endpoint( + monkeypatch: pytest.MonkeyPatch, +) -> None: + # DAPR_GRPC_ENDPOINT is user-supplied. If detect_target() raises on it, the gate + # must suppress the event rather than let the exception reach the runner. + clear_all_gate_vars(monkeypatch) + monkeypatch.setenv("DAPR_GRPC_ENDPOINT", "http://[:::::") + # Prove the input is not vacuous: it really makes detect_target() raise. + with pytest.raises(ValueError): + analytics.detect_target() + assert analytics.reo_allowed() is False + + +def test_reo_gate_fails_closed_when_a_check_raises( + monkeypatch: pytest.MonkeyPatch, +) -> None: + clear_all_gate_vars(monkeypatch) + + def boom() -> str: + raise RuntimeError("boom") + + monkeypatch.setattr(analytics, "detect_target", boom) + assert analytics.reo_allowed() is False + + +def test_reo_gate_is_not_vacuous_under_ci(monkeypatch: pytest.MonkeyPatch) -> None: + # Guards the Review Focus trap. + monkeypatch.setenv("CI", "true") + assert analytics.reo_allowed() is False + clear_all_gate_vars(monkeypatch) + assert analytics.reo_allowed() is True From d0187b534e70a1e53646bb1e9b1d662ad3ae8429 Mon Sep 17 00:00:00 2001 From: Marc Duiker <4191277+marcduiker@users.noreply.github.com> Date: Tue, 17 Nov 2026 11:25:51 +0100 Subject: [PATCH 3/9] feat(analytics): add the Reo destination for pypi_download Co-Authored-By: Claude Opus 5.5 Signed-off-by: Marc Duiker <4191277+marcduiker@users.noreply.github.com> --- diagrid/core/analytics.py | 81 +++++++++++++++-- tests/conftest.py | 10 ++- tests/core/test_analytics.py | 167 +++++++++++++++++++++++++++++++++-- 3 files changed, 236 insertions(+), 22 deletions(-) diff --git a/diagrid/core/analytics.py b/diagrid/core/analytics.py index 13269e60..e422a21f 100644 --- a/diagrid/core/analytics.py +++ b/diagrid/core/analytics.py @@ -18,8 +18,14 @@ blackholes lookups. The calling thread never waits on it. Blocked egress and air-gapped clusters are normal conditions, not faults. -Events go to every destination in ``USAGE_SINKS``. Set ``USAGE_ENDPOINT`` to an -empty string to turn the Scarf destination into a no-op. +Events go to every destination in ``USAGE_SINKS``: Scarf and Reo. Reo is gated +more strictly than Scarf (see ``reo_allowed``): it never receives events from +Kubernetes, Catalyst or CI. Set ``USAGE_ENDPOINT`` to an empty string to turn +the Scarf destination into a no-op, and ``REO_ENDPOINT`` to an empty string to +do the same for Reo. + +The destinations are sent to one after another on the same daemon thread, so a +slow Scarf send can delay the Reo send by up to the timeout. """ from __future__ import annotations @@ -43,6 +49,10 @@ USAGE_ENDPOINT = "https://diagrid.gateway.scarf.sh/python-ai" USAGE_TIMEOUT_SECONDS = 1.0 +# Reo event-collection endpoint. Reo accepts a GET with the meta keys as query +# parameters and no authentication. An empty string disables the destination. +REO_ENDPOINT = "https://telemetry.diagrid.io/data" + # The cross-ecosystem DO_NOT_TRACK convention, Scarf's own variable, and a # Diagrid-specific opt-out. Any of them set to a truthy value disables reporting. OPT_OUT_ENV_VARS = ("DO_NOT_TRACK", "SCARF_NO_ANALYTICS", "DIAGRID_NO_ANALYTICS") @@ -134,12 +144,13 @@ def _default_dimensions(package: str, version: str) -> dict[str, str]: } -def build_url(package: str, version: str, **dimensions: object) -> str: - """Build the Scarf event URL for ``package``. Exposed for tests. +def _merged_dimensions( + package: str, version: str, dimensions: Mapping[str, object] +) -> dict[str, str]: + """Return the defaults overlaid with the caller's dimensions, cleaned. - The defaults describe the package and the host. ``dimensions`` are added by - the caller (for example ``kind`` and ``framework``) and override a default - of the same name. Empty values are dropped. + ``None`` and empty values are dropped and every value is capped. Shared by + every destination so they cannot drift apart. """ params = _default_dimensions(package, version) for key, value in dimensions.items(): @@ -148,6 +159,17 @@ def build_url(package: str, version: str, **dimensions: object) -> str: cleaned = _clean_dimension(value) if cleaned: params[key] = cleaned + return params + + +def build_url(package: str, version: str, **dimensions: object) -> str: + """Build the Scarf event URL for ``package``. Exposed for tests. + + The defaults describe the package and the host. ``dimensions`` are added by + the caller (for example ``kind`` and ``framework``) and override a default + of the same name. Empty values are dropped. + """ + params = _merged_dimensions(package, version, dimensions) return f"{USAGE_ENDPOINT}?{urllib.parse.urlencode(params)}" @@ -189,8 +211,6 @@ def _scarf_request( configured=lambda: bool(USAGE_ENDPOINT), ) -USAGE_SINKS: tuple[Sink, ...] = (SCARF_SINK,) - def reo_allowed() -> bool: """Return True when a Reo event may be sent. Fails closed. @@ -212,6 +232,49 @@ def reo_allowed() -> bool: return False +# Collected name -> the key Reo registered. Names absent from this table (target +# and ci) are not sent to Reo: the gate makes both constant on every Reo event. +_REO_KEY_MAP = { + "package": "product", + "version": "version", + "python_version": "python", + "os": "platform", + "arch": "arch", + "kind": "kind", + "framework": "framework", + "framework_version": "framework_version", + "core_version": "core_version", +} + + +def build_reo_url(package: str, version: str, **dimensions: object) -> str: + """Build the Reo ``pypi_download`` event URL for ``package``. Exposed for tests.""" + merged = _merged_dimensions(package, version, dimensions) + params = {"activity_type": "pypi_download"} + for collected, reo_key in _REO_KEY_MAP.items(): + if collected in merged: + params[reo_key] = merged[collected] + return f"{REO_ENDPOINT}?{urllib.parse.urlencode(params)}" + + +def _reo_request(package: str, dimensions: Mapping[str, Any]) -> urllib.request.Request: + version = package_version(package) + return urllib.request.Request( + build_reo_url(package, version, **dimensions), + headers={"User-Agent": f"{package}/{version}"}, + ) + + +REO_SINK = Sink( + name="reo", + allowed=reo_allowed, + build_request=_reo_request, + configured=lambda: bool(REO_ENDPOINT), +) + +USAGE_SINKS: tuple[Sink, ...] = (SCARF_SINK, REO_SINK) + + def _send_event( package: str, dimensions: dict[str, object], diff --git a/tests/conftest.py b/tests/conftest.py index 9293846c..cf1c649a 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -10,10 +10,12 @@ def _no_usage_events(monkeypatch: pytest.MonkeyPatch) -> None: Every runner construction calls ``diagrid.core.analytics.report_usage``. With a live endpoint the first such call in a pytest run would start a real - daemon thread against the Scarf gateway, so every CI job and every local run - would count as usage. Blanking the endpoint makes the reporter a no-op, and - resetting the per-process guard gives every test a clean slate. Tests that - exercise the reporter itself set the endpoint explicitly. + daemon thread against the Scarf gateway and the Reo host, so every CI job + and every local run would count as usage. Blanking both endpoints makes the + reporter a no-op, and resetting the per-process guard gives every test a + clean slate. Tests that exercise the reporter itself set the endpoints + explicitly. """ monkeypatch.setattr("diagrid.core.analytics.USAGE_ENDPOINT", "") + monkeypatch.setattr("diagrid.core.analytics.REO_ENDPOINT", "") monkeypatch.setattr("diagrid.core.analytics._reported_packages", set()) diff --git a/tests/core/test_analytics.py b/tests/core/test_analytics.py index a3a13a84..2e7767bd 100644 --- a/tests/core/test_analytics.py +++ b/tests/core/test_analytics.py @@ -16,6 +16,16 @@ from diagrid.core import analytics ENDPOINT = "https://example.invalid/python-ai" +REO_TEST_ENDPOINT = "https://example.invalid/data" + +# The Scarf URL for the fixed inputs below. Shared by the documented-shape test +# and the test that Reo's dimensions leave Scarf's bytes alone. +SCARF_GOLDEN_URL = ( + "https://diagrid.gateway.scarf.sh/python-ai" + "?package=diagrid&version=0.5.3&core_version=0.5.3&os=linux&arch=x86_64" + "&python_version=3.12.1&target=dapr&ci=false&kind=workflow" + "&framework=langgraph&framework_version=0.2.0" +) _ENV_TO_CLEAR = ( *analytics.OPT_OUT_ENV_VARS, @@ -42,6 +52,7 @@ class Recorded(NamedTuple): url: str sink: str package: str + user_agent: str = "" class _SyncThread: @@ -85,6 +96,7 @@ def fake_urlopen(request: Any, timeout: float = 0) -> _Response: request.full_url, request.get_header("X-test-sink") or "", query.get("package", [""])[0], + request.get_header("User-agent") or "", ) ) return _Response() @@ -122,12 +134,7 @@ def test_scarf_url_is_the_documented_shape(monkeypatch: pytest.MonkeyPatch) -> N framework_version="0.2.0", ) assert len(recorded) == 1 - assert recorded[0].url == ( - "https://diagrid.gateway.scarf.sh/python-ai" - "?package=diagrid&version=0.5.3&core_version=0.5.3&os=linux&arch=x86_64" - "&python_version=3.12.1&target=dapr&ci=false&kind=workflow" - "&framework=langgraph&framework_version=0.2.0" - ) + assert recorded[0].url == SCARF_GOLDEN_URL def test_does_nothing_while_endpoint_is_empty(monkeypatch: pytest.MonkeyPatch) -> None: @@ -209,7 +216,10 @@ def test_send_uses_the_short_timeout_and_computes_the_version_once( patch.object(analytics.urllib.request, "urlopen") as urlopen, patch.object(analytics, "package_version", return_value="1.2.3") as version, ): - analytics._send_event("diagrid", {"kind": "agent"}) + # Scarf only: this test pins one send. Reo's is covered separately. + analytics._send_event( + "diagrid", {"kind": "agent"}, sinks=(analytics.SCARF_SINK,) + ) _, kwargs = urlopen.call_args assert kwargs["timeout"] == analytics.USAGE_TIMEOUT_SECONDS request = urlopen.call_args.args[0] @@ -412,9 +422,10 @@ def explode() -> bool: assert {r.sink for r in recorded} == {"b"} -def test_scarf_is_the_default_destination() -> None: - assert analytics.USAGE_SINKS == (analytics.SCARF_SINK,) +def test_scarf_and_reo_are_the_default_destinations() -> None: + assert analytics.USAGE_SINKS == (analytics.SCARF_SINK, analytics.REO_SINK) assert analytics.SCARF_SINK.name == "scarf" + assert analytics.REO_SINK.name == "reo" def clear_all_gate_vars(monkeypatch: pytest.MonkeyPatch) -> None: @@ -511,3 +522,141 @@ def test_reo_gate_is_not_vacuous_under_ci(monkeypatch: pytest.MonkeyPatch) -> No assert analytics.reo_allowed() is False clear_all_gate_vars(monkeypatch) assert analytics.reo_allowed() is True + + +def query_of(url: str) -> dict[str, list[str]]: + return urllib.parse.parse_qs(urllib.parse.urlsplit(url).query) + + +def _reo_setup(monkeypatch: pytest.MonkeyPatch) -> list[Recorded]: + """Point Reo at a non-routable host, record sends, pin the package version.""" + monkeypatch.setattr(analytics, "REO_ENDPOINT", REO_TEST_ENDPOINT) + recorded = record_requests(monkeypatch) + clear_all_gate_vars(monkeypatch) + # ``version`` is the installed version of the package, not a dimension. + monkeypatch.setattr(analytics, "package_version", lambda _package: "0.5.3") + return recorded + + +def test_reo_url_maps_collected_names_to_registered_keys( + monkeypatch: pytest.MonkeyPatch, +) -> None: + recorded = _reo_setup(monkeypatch) + analytics.report_usage( + "diagrid", + sinks=(analytics.REO_SINK,), + python_version="3.12.1", + os="linux", + arch="x86_64", + target="dapr", + ci="false", + ) + assert len(recorded) == 1 + assert recorded[0].url.startswith(REO_TEST_ENDPOINT + "?") + q = query_of(recorded[0].url) + assert q["activity_type"] == ["pypi_download"] + assert q["product"] == ["diagrid"] + assert q["version"] == ["0.5.3"] + assert q["python"] == ["3.12.1"] + assert q["platform"] == ["linux"] + assert q["arch"] == ["x86_64"] + assert recorded[0].user_agent == "diagrid/0.5.3" + + +def test_reo_url_keeps_names_that_need_no_mapping( + monkeypatch: pytest.MonkeyPatch, +) -> None: + recorded = _reo_setup(monkeypatch) + analytics.report_usage( + "diagrid", + sinks=(analytics.REO_SINK,), + core_version="0.5.3", + kind="workflow", + framework="langgraph", + framework_version="0.2.0", + ) + q = query_of(recorded[0].url) + assert q["core_version"] == ["0.5.3"] + assert q["kind"] == ["workflow"] + assert q["framework"] == ["langgraph"] + assert q["framework_version"] == ["0.2.0"] + + +def test_reo_url_omits_target_and_ci(monkeypatch: pytest.MonkeyPatch) -> None: + recorded = _reo_setup(monkeypatch) + analytics.report_usage( + "diagrid", sinks=(analytics.REO_SINK,), target="dapr", ci="false" + ) + q = query_of(recorded[0].url) + assert "target" not in q and "ci" not in q + # and the unmapped source names must not leak through either + assert "os" not in q and "python_version" not in q and "package" not in q + + +def test_reo_url_drops_none_dimensions(monkeypatch: pytest.MonkeyPatch) -> None: + recorded = _reo_setup(monkeypatch) + analytics.report_usage( + "diagrid", sinks=(analytics.REO_SINK,), framework_version=None, kind="" + ) + q = query_of(recorded[0].url) + assert "framework_version" not in q # never the string "None" + assert "kind" not in q + + +def test_reo_url_escapes_hostile_values(monkeypatch: pytest.MonkeyPatch) -> None: + recorded = _reo_setup(monkeypatch) + analytics.report_usage("diagrid", sinks=(analytics.REO_SINK,), framework="a&b=c") + q = query_of(recorded[0].url) + assert q["framework"] == ["a&b=c"] # one parameter, not two + assert "b" not in q + + +def test_reo_url_bounds_long_values(monkeypatch: pytest.MonkeyPatch) -> None: + recorded = _reo_setup(monkeypatch) + analytics.report_usage("diagrid", sinks=(analytics.REO_SINK,), framework="x" * 200) + assert query_of(recorded[0].url)["framework"] == ["x" * 64] + + +def test_reo_is_a_no_op_while_its_endpoint_is_empty( + monkeypatch: pytest.MonkeyPatch, +) -> None: + recorded = _reo_setup(monkeypatch) + monkeypatch.setattr(analytics, "REO_ENDPOINT", "") + analytics.report_usage("diagrid", sinks=(analytics.REO_SINK,)) + assert recorded == [] + + +def test_reo_is_not_sent_when_its_gate_is_closed( + monkeypatch: pytest.MonkeyPatch, +) -> None: + recorded = _reo_setup(monkeypatch) + monkeypatch.setenv("KUBERNETES_SERVICE_HOST", "10.0.0.1") + analytics.report_usage("diagrid", sinks=(analytics.REO_SINK,)) + assert recorded == [] + + +def test_scarf_url_is_unchanged_by_reo_dimensions( + monkeypatch: pytest.MonkeyPatch, +) -> None: + # Adding Reo must not move Scarf's bytes, with both sinks live. + monkeypatch.setattr( + analytics, "USAGE_ENDPOINT", "https://diagrid.gateway.scarf.sh/python-ai" + ) + recorded = _reo_setup(monkeypatch) + analytics.report_usage( + "diagrid", + core_version="0.5.3", + os="linux", + arch="x86_64", + python_version="3.12.1", + target="dapr", + ci="false", + kind="workflow", + framework="langgraph", + framework_version="0.2.0", + ) + assert len(recorded) == 2 + scarf = next(r for r in recorded if "scarf.sh" in r.url) + assert scarf.url == SCARF_GOLDEN_URL + assert scarf.user_agent == "diagrid/0.5.3" + assert any(r.url.startswith(REO_TEST_ENDPOINT) for r in recorded) From 52821e411efbb2ea1c7fe488492365a93566ef08 Mon Sep 17 00:00:00 2001 From: Marc Duiker <4191277+marcduiker@users.noreply.github.com> Date: Tue, 17 Nov 2026 11:32:16 +0100 Subject: [PATCH 4/9] feat(cli): report diagrid-cli usage to Reo once per process Co-Authored-By: Claude Opus 5.5 Signed-off-by: Marc Duiker <4191277+marcduiker@users.noreply.github.com> --- diagrid/agent/core/workflow/runner.py | 12 ++- diagrid/cli/main.py | 27 ++++- diagrid/core/analytics.py | 69 +++++++++---- tests/cli/test_main.py | 142 ++++++++++++++++++++++++++ 4 files changed, 227 insertions(+), 23 deletions(-) diff --git a/diagrid/agent/core/workflow/runner.py b/diagrid/agent/core/workflow/runner.py index d5df690a..bc1f735a 100644 --- a/diagrid/agent/core/workflow/runner.py +++ b/diagrid/agent/core/workflow/runner.py @@ -8,9 +8,10 @@ import logging import uuid from abc import ABC, abstractmethod +from collections.abc import Sequence from contextlib import asynccontextmanager from importlib import metadata -from typing import Any, AsyncIterator, Optional +from typing import TYPE_CHECKING, Any, AsyncIterator, Optional from dapr.ext.workflow import DaprWorkflowClient, WorkflowRuntime, WorkflowStatus from dapr_agents.utils.signal.mixin import SignalMixin @@ -23,11 +24,16 @@ # ``diagrid-core`` ships the reporter. This distribution only pins # ``diagrid-core>=0.1.0`` (through ``diagrid-cli``), so an application holding # an older ``diagrid-core`` must keep working: fall back to a no-op. +if TYPE_CHECKING: + from diagrid.core.analytics import Sink + try: from diagrid.core.analytics import report_usage except ImportError: # pragma: no cover - older diagrid-core - # The fallback has no ``sinks`` parameter: an older core has no destination list. - def report_usage(package: str, **dimensions: object) -> None: # type: ignore[misc] + # ``sinks`` is accepted and ignored: an older core has no destination list. + def report_usage( + package: str, *, sinks: Sequence["Sink"] = (), **dimensions: object + ) -> None: return None diff --git a/diagrid/cli/main.py b/diagrid/cli/main.py index 9813086c..420c18c9 100644 --- a/diagrid/cli/main.py +++ b/diagrid/cli/main.py @@ -5,16 +5,41 @@ from __future__ import annotations +import logging +from typing import Any + import click from diagrid.cli.commands.chaos import chaos from diagrid.cli.commands.deploy import deploy from diagrid.cli.commands.init import init from diagrid.cli.utils.process import set_verbose +from diagrid.core import analytics from diagrid.core.config.constants import PROD_API_URL, STAGING_API_URL -@click.group() +def _report_cli_usage() -> None: + """Report one anonymous usage event to Reo. Never raises, never prints.""" + try: + analytics.report_usage_blocking("diagrid-cli", sinks=(analytics.REO_SINK,)) + except Exception: + logging.getLogger(__name__).debug("cli usage report failed", exc_info=True) + + +class _UsageReportingGroup(click.Group): + """A group that reports usage before it parses anything. + + ``--help`` and ``--version`` are eager options: click handles them while + parsing, before the group callback runs. ``main`` is the one point every + invocation passes through, including ``CliRunner.invoke``. + """ + + def main(self, *args: Any, **kwargs: Any) -> Any: + _report_cli_usage() + return super().main(*args, **kwargs) + + +@click.group(cls=_UsageReportingGroup) # Read the version from the installed ``diagrid-cli`` distribution rather than # hardcoding it. The release workflow bumps ``diagrid/cli/pyproject.toml`` but # never touched a literal here, so a hardcoded string silently goes stale. diff --git a/diagrid/core/analytics.py b/diagrid/core/analytics.py index e422a21f..e2bae0b6 100644 --- a/diagrid/core/analytics.py +++ b/diagrid/core/analytics.py @@ -293,6 +293,36 @@ def _send_event( ) +def _select_sinks(package: str, sinks: Sequence[Sink]) -> list[Sink]: + """Return the sinks that should receive ``package``'s event, marking them reported. + + Shared by ``report_usage`` and ``report_usage_blocking`` so the dedupe set + and the gates cannot drift apart. A sink is skipped while it has no + endpoint, once it has already seen this package in this process, or when its + gate is closed. Never raises. + """ + selected: list[Sink] = [] + for sink in sinks: + try: + if not sink.configured(): + continue + key = (sink.name, package) + with _reported_lock: + if key in _reported_packages: + continue + _reported_packages.add(key) + + if not sink.allowed(): + logger.debug( + "usage reporting for %s to %s is disabled", package, sink.name + ) + continue + selected.append(sink) + except Exception: + continue + return selected + + def report_usage( package: str, *, sinks: Sequence[Sink] = USAGE_SINKS, **dimensions: object ) -> None: @@ -305,25 +335,7 @@ def report_usage( closed, for example when the user opted out. """ try: - selected: list[Sink] = [] - for sink in sinks: - try: - if not sink.configured(): - continue - key = (sink.name, package) - with _reported_lock: - if key in _reported_packages: - continue - _reported_packages.add(key) - - if not sink.allowed(): - logger.debug( - "usage reporting for %s to %s is disabled", package, sink.name - ) - continue - selected.append(sink) - except Exception: - continue + selected = _select_sinks(package, sinks) if not selected: return @@ -337,3 +349,22 @@ def report_usage( thread.start() except Exception: pass + + +def report_usage_blocking( + package: str, *, sinks: Sequence[Sink], **dimensions: object +) -> None: + """Report like ``report_usage``, but send on the calling thread. + + For a one-shot process, such as a CLI command, that exits before a daemon + thread would finish. The caller waits for the send. Each socket operation + is capped at ``USAGE_TIMEOUT_SECONDS``, so a host that accepts and never + replies costs about that long per destination. DNS resolution is not + covered by that cap. Never raises. + """ + try: + selected = _select_sinks(package, sinks) + if selected: + _send_event(package, dict(dimensions), sinks=tuple(selected)) + except Exception: + pass diff --git a/tests/cli/test_main.py b/tests/cli/test_main.py index a69e1207..6a9e65e8 100644 --- a/tests/cli/test_main.py +++ b/tests/cli/test_main.py @@ -4,10 +4,18 @@ """Tests for CLI main entry point — env/api flag handling.""" from __future__ import annotations + +import socket +import time +import urllib.parse +from typing import Any + import click +import pytest from click.testing import CliRunner from diagrid.cli.main import cli +from diagrid.core import analytics from diagrid.core.config.constants import PROD_API_URL, STAGING_API_URL @@ -54,3 +62,137 @@ def test_cli_no_env_sets_none() -> None: result = _invoke_noop() assert result.exit_code == 0, result.output assert "api_url=None" in result.output + + +# --- Usage reporting (Reo only, blocking, once per process) ----------------- + +REO_TEST_ENDPOINT = "https://example.invalid/data" + +_GATE_ENV_VARS = ( + *analytics.OPT_OUT_ENV_VARS, + *analytics._CI_TRUTHY_ENV_VARS, + *analytics._CI_PRESENCE_ENV_VARS, + *analytics._DAPR_ENDPOINT_ENV_VARS, + "DAPR_API_TOKEN", + "KUBERNETES_SERVICE_HOST", +) + + +def clear_all_gate_vars(monkeypatch: pytest.MonkeyPatch) -> None: + for name in _GATE_ENV_VARS: + monkeypatch.delenv(name, raising=False) + + +class _Response: + def __enter__(self) -> "_Response": + return self + + def __exit__(self, *_: Any) -> None: + return None + + +def record_requests(monkeypatch: pytest.MonkeyPatch) -> list[str]: + """Record the URL of every request instead of sending it.""" + recorded: list[str] = [] + + def fake_urlopen(request: Any, timeout: float = 0) -> _Response: + recorded.append(request.full_url) + return _Response() + + monkeypatch.setattr(analytics.urllib.request, "urlopen", fake_urlopen) + return recorded + + +def invoke_cli(args: list[str]) -> "click.testing.Result": + return CliRunner().invoke(cli, args) + + +def test_cli_reports_to_reo_only(monkeypatch: pytest.MonkeyPatch) -> None: + monkeypatch.setattr(analytics, "REO_ENDPOINT", REO_TEST_ENDPOINT) + # Scarf stays configured, so only the explicit sink list keeps it out. + monkeypatch.setattr(analytics, "USAGE_ENDPOINT", "https://scarf.example.invalid/x") + recorded = record_requests(monkeypatch) + clear_all_gate_vars(monkeypatch) + invoke_cli(["--help"]) + assert len(recorded) == 1 + assert recorded[0].startswith(REO_TEST_ENDPOINT + "?") + query = urllib.parse.parse_qs(urllib.parse.urlsplit(recorded[0]).query) + assert query["product"] == ["diagrid-cli"] + assert query["activity_type"] == ["pypi_download"] + assert "kind" not in query + assert "framework" not in query + assert not any("scarf" in url for url in recorded) + + +@pytest.mark.parametrize("args", [["--version"], ["--help"], ["deploy", "--help"]]) +def test_cli_reports_on_eager_flags( + monkeypatch: pytest.MonkeyPatch, args: list[str] +) -> None: + monkeypatch.setattr(analytics, "REO_ENDPOINT", REO_TEST_ENDPOINT) + recorded = record_requests(monkeypatch) + clear_all_gate_vars(monkeypatch) + result = invoke_cli(args) + assert result.exit_code == 0, result.output + assert len(recorded) == 1 + + +def test_cli_send_is_blocking_and_capped(monkeypatch: pytest.MonkeyPatch) -> None: + # A one-shot CLI exits before a daemon thread finishes, so the send blocks, + # and must therefore be bounded. The server accepts and never replies. + server = socket.socket(socket.AF_INET, socket.SOCK_STREAM) + try: + server.bind(("127.0.0.1", 0)) + server.listen(1) + port = server.getsockname()[1] + monkeypatch.setattr(analytics, "REO_ENDPOINT", f"http://127.0.0.1:{port}/data") + monkeypatch.setattr(analytics, "USAGE_TIMEOUT_SECONDS", 1.0) + clear_all_gate_vars(monkeypatch) + + start = time.monotonic() + analytics.report_usage_blocking("diagrid-cli", sinks=(analytics.REO_SINK,)) + elapsed = time.monotonic() - start + finally: + server.close() + assert elapsed < 3.0 + assert elapsed >= 0.5 # it really waited on the socket, not skipped the send + + +def test_cli_exits_zero_when_telemetry_fails(monkeypatch: pytest.MonkeyPatch) -> None: + # A port that was just closed refuses connections immediately. + probe = socket.socket(socket.AF_INET, socket.SOCK_STREAM) + probe.bind(("127.0.0.1", 0)) + port = probe.getsockname()[1] + probe.close() + monkeypatch.setattr(analytics, "REO_ENDPOINT", f"http://127.0.0.1:{port}/data") + clear_all_gate_vars(monkeypatch) + result = invoke_cli(["--help"]) + assert result.exit_code == 0 + assert "telemetry" not in result.output.lower() + assert "diagrid.io" not in result.output + + +def test_cli_exits_zero_when_reporter_raises(monkeypatch: pytest.MonkeyPatch) -> None: + def boom(*_: Any, **__: Any) -> None: + raise RuntimeError("boom") + + monkeypatch.setattr(analytics, "report_usage_blocking", boom) + result = invoke_cli(["--help"]) + assert result.exit_code == 0 + + +def test_cli_sends_nothing_when_opted_out(monkeypatch: pytest.MonkeyPatch) -> None: + monkeypatch.setattr(analytics, "REO_ENDPOINT", REO_TEST_ENDPOINT) + recorded = record_requests(monkeypatch) + clear_all_gate_vars(monkeypatch) + monkeypatch.setenv("DO_NOT_TRACK", "1") + invoke_cli(["--help"]) + assert recorded == [] + + +def test_cli_reports_once_per_process(monkeypatch: pytest.MonkeyPatch) -> None: + monkeypatch.setattr(analytics, "REO_ENDPOINT", REO_TEST_ENDPOINT) + recorded = record_requests(monkeypatch) + clear_all_gate_vars(monkeypatch) + invoke_cli(["--help"]) + invoke_cli(["--version"]) + assert len(recorded) == 1 From f22b4afe629a15726b120a204ad3e17b7f7357b0 Mon Sep 17 00:00:00 2001 From: Marc Duiker <4191277+marcduiker@users.noreply.github.com> Date: Tue, 17 Nov 2026 11:34:23 +0100 Subject: [PATCH 5/9] docs: document Reo usage analytics and how to turn it off Co-Authored-By: Claude Opus 5.5 Signed-off-by: Marc Duiker <4191277+marcduiker@users.noreply.github.com> --- README.md | 27 +++++++++++++++++++++++---- 1 file changed, 23 insertions(+), 4 deletions(-) diff --git a/README.md b/README.md index ad389cdc..1fcdaaee 100644 --- a/README.md +++ b/README.md @@ -62,13 +62,32 @@ pip install "diagrid[holmesgpt]" ## Usage analytics -Every agent runner reports one anonymous usage event when it is constructed, once per package per process. PyPI publishes aggregate download counts only, so this is how Diagrid sees which package versions run on which platforms. Because it is one event per process, a Kubernetes deployment produces one event per replica per restart: the numbers count process starts, not deployments or users. +Diagrid reports anonymous usage events to two services, [Scarf](https://scarf.sh) and [Reo](https://www.reo.dev). PyPI publishes aggregate download counts only, so these events show which package versions run on which platforms. Both services derive coarse company and location information from the request IP. How they handle that data is described in [Scarf's privacy policy](https://about.scarf.sh/privacy-policy) and [Reo's privacy policy](https://www.reo.dev/privacy-policy). -**What is sent:** the package name and version, the `diagrid-core` version, operating system, architecture, Python version, the agent framework and the installed version of its library (`framework`, `framework_version`), `kind=agent`, whether the process points at Catalyst or at a plain Dapr sidecar (`target`), and whether it runs under a CI variable (`ci`). Nothing else: no application data, configuration, app IDs, prompts, or hostnames. The receiving service is [Scarf](https://scarf.sh). It derives coarse company and location information from the request IP. How Scarf handles that data is described in [Scarf's privacy policy](https://about.scarf.sh/privacy-policy). +Every agent runner reports one event when it is constructed, once per package per process. It goes to Scarf and Reo. Because it is one event per process, a Kubernetes deployment produces one event per replica per restart: the numbers count process starts, not deployments or users. -**It never gets in the way:** the request runs on a background daemon thread with a one second socket timeout, every failure is swallowed, and the calling thread never waits. Blocked egress and air-gapped clusters behave normally. Nothing is written to your application's output; a `DEBUG` line on the `diagrid.core.analytics` logger records whether the event was sent or skipped, for operators who want to confirm an opt-out. +`diagridpy`, the console script for `diagrid-cli`, reports to Reo only. It sends one event per invocation, including `--help` and `--version`. The send blocks the command for at most about one second per socket operation. That timeout does not cover DNS resolution, so a network that stalls lookups can delay the command for longer. -To opt out, set any of these environment variables before starting your application: +**What is sent:** the package name and version, the `diagrid-core` version, operating system, architecture, Python version, and, for agent runners, the agent framework and the installed version of its library. Nothing else: no prompts, application data, configuration, app IDs, hostnames, or file paths. + +| | Scarf | Reo | +|---|---|---| +| Sent by | agent runners | agent runners and `diagridpy` | +| Fields | `package`, `version`, `core_version`, `os`, `arch`, `python_version`, `kind`, `framework`, `framework_version`, `target`, `ci` | `activity_type=pypi_download`, `product`, `version`, `python`, `platform`, `arch`, `kind`, `framework`, `framework_version`, `core_version` | +| `target` and `ci` | sent | not sent | + +`target` says whether the process points at Catalyst or at a plain Dapr sidecar. `ci` says whether a CI variable is set. + +**When Reo is skipped:** Reo is not contacted from Kubernetes, from CI, or when the process points at Catalyst. Scarf is still contacted in those cases, so the two services report different totals. Reo is skipped when any of these is true: + +- you set an opt-out variable (see below) +- `KUBERNETES_SERVICE_HOST` is set +- `DAPR_GRPC_ENDPOINT` or `DAPR_HTTP_ENDPOINT` points at a host under `diagrid.io`, or `DAPR_API_TOKEN` is set +- a CI variable is set, such as `CI`, `GITHUB_ACTIONS` or `GITLAB_CI` + +**It never gets in the way:** agent runners send on a background daemon thread with a one second socket timeout, every failure is swallowed, and the calling thread never waits. Blocked egress and air-gapped clusters behave normally. Nothing is written to your application's output. A `DEBUG` line on the `diagrid.core.analytics` logger records whether each event was sent or skipped, for operators who want to confirm an opt-out. + +To opt out of both services, set any of these environment variables before starting your application or running `diagridpy`: ```bash export DO_NOT_TRACK=1 From a9a2842c5b81361a6d9ac48d8e4554e3758bd44d Mon Sep 17 00:00:00 2001 From: Marc Duiker <4191277+marcduiker@users.noreply.github.com> Date: Tue, 17 Nov 2026 11:41:26 +0100 Subject: [PATCH 6/9] fix(cli): skip usage reporting for shell completion and missing analytics Co-Authored-By: Claude Opus 5.5 Signed-off-by: Marc Duiker <4191277+marcduiker@users.noreply.github.com> --- diagrid/cli/main.py | 47 +++++++++++++++++++++++++++++++++++---- tests/cli/test_main.py | 50 ++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 93 insertions(+), 4 deletions(-) diff --git a/diagrid/cli/main.py b/diagrid/cli/main.py index 420c18c9..920c0853 100644 --- a/diagrid/cli/main.py +++ b/diagrid/cli/main.py @@ -6,6 +6,8 @@ from __future__ import annotations import logging +import os +import sys from typing import Any import click @@ -14,12 +16,41 @@ from diagrid.cli.commands.deploy import deploy from diagrid.cli.commands.init import init from diagrid.cli.utils.process import set_verbose -from diagrid.core import analytics from diagrid.core.config.constants import PROD_API_URL, STAGING_API_URL +# ``diagrid.core.analytics`` first shipped in diagrid-core 0.5.1, but this +# package pins ``diagrid-core>=0.1.0``. With an older core the CLI must still +# run, so fall back to no reporting. +try: + from diagrid.core import analytics +except ImportError: # pragma: no cover - older diagrid-core + analytics = None # type: ignore[assignment] + + +def _is_completion_request(prog_name: str | None, complete_var: str | None) -> bool: + """Return True when click will treat this invocation as shell completion. + + Mirrors ``click.Command._main_shell_completion``: the variable is + ``complete_var`` when given, else ``_{PROG_NAME}_COMPLETE`` upper-cased with + ``-`` and ``.`` in the program name replaced by ``_``. Click then exits + after printing the script or the completions, so such a call must neither + report nor block (``eval "$(_DIAGRIDPY_COMPLETE=zsh_source diagridpy)"`` + runs on every new terminal). + """ + try: + if complete_var is None: + name = prog_name or os.path.basename(sys.argv[0]) + name = name.replace("-", "_").replace(".", "_") + complete_var = f"_{name}_COMPLETE".upper() + return bool(os.environ.get(complete_var)) + except Exception: + return False + def _report_cli_usage() -> None: """Report one anonymous usage event to Reo. Never raises, never prints.""" + if analytics is None: + return try: analytics.report_usage_blocking("diagrid-cli", sinks=(analytics.REO_SINK,)) except Exception: @@ -34,9 +65,17 @@ class _UsageReportingGroup(click.Group): invocation passes through, including ``CliRunner.invoke``. """ - def main(self, *args: Any, **kwargs: Any) -> Any: - _report_cli_usage() - return super().main(*args, **kwargs) + def main( + self, + args: Any = None, + prog_name: str | None = None, + complete_var: str | None = None, + *rest: Any, + **kwargs: Any, + ) -> Any: + if not _is_completion_request(prog_name, complete_var): + _report_cli_usage() + return super().main(args, prog_name, complete_var, *rest, **kwargs) @click.group(cls=_UsageReportingGroup) diff --git a/tests/cli/test_main.py b/tests/cli/test_main.py index 6a9e65e8..cdce0c33 100644 --- a/tests/cli/test_main.py +++ b/tests/cli/test_main.py @@ -5,7 +5,9 @@ from __future__ import annotations +import importlib import socket +import sys import time import urllib.parse from typing import Any @@ -196,3 +198,51 @@ def test_cli_reports_once_per_process(monkeypatch: pytest.MonkeyPatch) -> None: invoke_cli(["--help"]) invoke_cli(["--version"]) assert len(recorded) == 1 + + +def test_cli_skips_reporting_for_shell_completion( + monkeypatch: pytest.MonkeyPatch, +) -> None: + monkeypatch.setattr(analytics, "REO_ENDPOINT", REO_TEST_ENDPOINT) + recorded = record_requests(monkeypatch) + clear_all_gate_vars(monkeypatch) + # Positive control: the same setup without the variable does report. + CliRunner().invoke(cli, ["--help"], prog_name="diagridpy") + assert len(recorded) == 1 + + monkeypatch.setattr(analytics, "_reported_packages", set()) + recorded.clear() + CliRunner().invoke( + cli, [], prog_name="diagridpy", env={"_DIAGRIDPY_COMPLETE": "bash_source"} + ) + assert recorded == [] + + +def test_cli_skips_reporting_for_completion_with_custom_complete_var( + monkeypatch: pytest.MonkeyPatch, +) -> None: + monkeypatch.setattr(analytics, "REO_ENDPOINT", REO_TEST_ENDPOINT) + recorded = record_requests(monkeypatch) + clear_all_gate_vars(monkeypatch) + monkeypatch.setenv("_CUSTOM_VAR", "bash_source") + with pytest.raises(SystemExit): + cli.main([], prog_name="diagridpy", complete_var="_CUSTOM_VAR") + assert recorded == [] + + +def test_cli_runs_without_the_analytics_module() -> None: + # An older diagrid-core has no diagrid.core.analytics: the CLI must still run. + import diagrid.cli.main as main_module + import diagrid.core + + try: + with pytest.MonkeyPatch.context() as mp: + mp.setitem(sys.modules, "diagrid.core.analytics", None) + mp.delattr(diagrid.core, "analytics") + reloaded = importlib.reload(main_module) + assert reloaded.analytics is None + result = CliRunner().invoke(reloaded.cli, ["--help"]) + assert result.exit_code == 0, result.output + finally: + importlib.reload(main_module) + assert main_module.analytics is not None From bb01be1b045fdeb28a975cce06ab9e6b8ed0d931 Mon Sep 17 00:00:00 2001 From: Marc Duiker <4191277+marcduiker@users.noreply.github.com> Date: Tue, 17 Nov 2026 11:41:26 +0100 Subject: [PATCH 7/9] fix(analytics): cap the blocking send at the timeout Co-Authored-By: Claude Opus 5.5 Signed-off-by: Marc Duiker <4191277+marcduiker@users.noreply.github.com> --- README.md | 4 ++-- diagrid/core/analytics.py | 39 +++++++++++++++++++++----------- tests/core/test_analytics.py | 43 ++++++++++++++++++++++++++++++++++++ 3 files changed, 71 insertions(+), 15 deletions(-) diff --git a/README.md b/README.md index 1fcdaaee..fd3ae4c7 100644 --- a/README.md +++ b/README.md @@ -66,14 +66,14 @@ Diagrid reports anonymous usage events to two services, [Scarf](https://scarf.sh Every agent runner reports one event when it is constructed, once per package per process. It goes to Scarf and Reo. Because it is one event per process, a Kubernetes deployment produces one event per replica per restart: the numbers count process starts, not deployments or users. -`diagridpy`, the console script for `diagrid-cli`, reports to Reo only. It sends one event per invocation, including `--help` and `--version`. The send blocks the command for at most about one second per socket operation. That timeout does not cover DNS resolution, so a network that stalls lookups can delay the command for longer. +`diagridpy`, the console script for `diagrid-cli`, reports to Reo only. It sends one event per invocation, including `--help` and `--version`. The send blocks the command for at most about one second in total, a hard cap that includes DNS resolution. A send still running at the cap is abandoned. Shell completion requests are not reported. **What is sent:** the package name and version, the `diagrid-core` version, operating system, architecture, Python version, and, for agent runners, the agent framework and the installed version of its library. Nothing else: no prompts, application data, configuration, app IDs, hostnames, or file paths. | | Scarf | Reo | |---|---|---| | Sent by | agent runners | agent runners and `diagridpy` | -| Fields | `package`, `version`, `core_version`, `os`, `arch`, `python_version`, `kind`, `framework`, `framework_version`, `target`, `ci` | `activity_type=pypi_download`, `product`, `version`, `python`, `platform`, `arch`, `kind`, `framework`, `framework_version`, `core_version` | +| Fields | `package`, `version`, `core_version`, `os`, `arch`, `python_version`, `target`, `ci`, plus `kind` (`agent`), `framework` and `framework_version` from agent runners only | `activity_type=pypi_download`, `product`, `version`, `python`, `platform`, `arch`, `core_version`, plus `kind` (`agent`), `framework` and `framework_version` from agent runners only | | `target` and `ci` | sent | not sent | `target` says whether the process points at Catalyst or at a plain Dapr sidecar. `ci` says whether a CI variable is set. diff --git a/diagrid/core/analytics.py b/diagrid/core/analytics.py index e2bae0b6..335f9cfa 100644 --- a/diagrid/core/analytics.py +++ b/diagrid/core/analytics.py @@ -12,12 +12,15 @@ One event per process means one event per replica per restart on Kubernetes. The numbers count process starts, not deployments or users. -The call never blocks and never raises: it runs on a daemon thread and swallows -every failure. The one second timeout bounds each socket operation, not DNS -resolution, so the thread itself can outlive a second on a network that -blackholes lookups. The calling thread never waits on it. Blocked egress and +``report_usage`` never blocks and never raises: it runs on a daemon thread and +swallows every failure. The calling thread never waits on it. Blocked egress and air-gapped clusters are normal conditions, not faults. +``report_usage_blocking`` is for one-shot processes such as the CLI. It sends on +the same kind of daemon thread but joins it for at most ``USAGE_TIMEOUT_SECONDS``, +a hard wall-clock cap that includes DNS resolution. A send still running at the +cap is abandoned and dies with the process. + Events go to every destination in ``USAGE_SINKS``: Scarf and Reo. Reo is gated more strictly than Scarf (see ``reo_allowed``): it never receives events from Kubernetes, Catalyst or CI. Set ``USAGE_ENDPOINT`` to an empty string to turn @@ -25,7 +28,8 @@ do the same for Reo. The destinations are sent to one after another on the same daemon thread, so a -slow Scarf send can delay the Reo send by up to the timeout. +slow Scarf send can delay the Reo send by up to the timeout. In the blocking +variant the cap covers all destinations together. """ from __future__ import annotations @@ -354,17 +358,26 @@ def report_usage( def report_usage_blocking( package: str, *, sinks: Sequence[Sink], **dimensions: object ) -> None: - """Report like ``report_usage``, but send on the calling thread. + """Report like ``report_usage``, but wait for the send, for at most the timeout. - For a one-shot process, such as a CLI command, that exits before a daemon - thread would finish. The caller waits for the send. Each socket operation - is capped at ``USAGE_TIMEOUT_SECONDS``, so a host that accepts and never - replies costs about that long per destination. DNS resolution is not - covered by that cap. Never raises. + For a one-shot process, such as a CLI command, that exits before a fire and + forget thread would finish. The send runs on a daemon thread and the caller + joins it for at most ``USAGE_TIMEOUT_SECONDS``, a hard wall-clock cap that + also covers DNS resolution. A send still in flight at the cap is abandoned + and dies with the process. Never raises. """ try: selected = _select_sinks(package, sinks) - if selected: - _send_event(package, dict(dimensions), sinks=tuple(selected)) + if not selected: + return + thread = threading.Thread( + target=_send_event, + args=(package, dict(dimensions)), + kwargs={"sinks": tuple(selected)}, + name="diagrid-usage", + daemon=True, + ) + thread.start() + thread.join(USAGE_TIMEOUT_SECONDS) except Exception: pass diff --git a/tests/core/test_analytics.py b/tests/core/test_analytics.py index 2e7767bd..687eb7ea 100644 --- a/tests/core/test_analytics.py +++ b/tests/core/test_analytics.py @@ -660,3 +660,46 @@ def test_scarf_url_is_unchanged_by_reo_dimensions( assert scarf.url == SCARF_GOLDEN_URL assert scarf.user_agent == "diagrid/0.5.3" assert any(r.url.startswith(REO_TEST_ENDPOINT) for r in recorded) + + +def test_reo_url_drops_unknown_dimensions_and_cannot_override_product( + monkeypatch: pytest.MonkeyPatch, +) -> None: + # The allowlist is the privacy guarantee: an arbitrary dimension never + # reaches Reo, and a caller cannot rewrite the product. + recorded = _reo_setup(monkeypatch) + analytics.report_usage( + "diagrid", sinks=(analytics.REO_SINK,), hostname="secret-host", product="evil" + ) + assert len(recorded) == 1 + assert "secret-host" not in recorded[0].url + q = query_of(recorded[0].url) + assert "hostname" not in q + assert q["product"] == ["diagrid"] + + +def test_blocking_send_is_capped_when_the_send_itself_stalls( + monkeypatch: pytest.MonkeyPatch, +) -> None: + # DNS and other stalls are not covered by the socket timeout. The caller + # still gets control back at the cap. The stalled send is released in + # teardown so no thread outlives the test. + import threading + import time + + release = threading.Event() + + def stalled_send(*_: Any, **__: Any) -> None: + release.wait(10) + + monkeypatch.setattr(analytics, "REO_ENDPOINT", REO_TEST_ENDPOINT) + monkeypatch.setattr(analytics, "_send_event", stalled_send) + clear_all_gate_vars(monkeypatch) + try: + start = time.monotonic() + analytics.report_usage_blocking("diagrid-cli", sinks=(analytics.REO_SINK,)) + elapsed = time.monotonic() - start + finally: + release.set() + assert elapsed < 1.5 + assert elapsed >= 0.5 # it waited for the send up to the cap From 8e15c89a75e76c65bb5dda7713efe083c1c750ef Mon Sep 17 00:00:00 2001 From: Marc Duiker <4191277+marcduiker@users.noreply.github.com> Date: Tue, 17 Nov 2026 11:41:40 +0100 Subject: [PATCH 8/9] test(cli): tighten the blocking send bound to the hard cap Co-Authored-By: Claude Opus 5.5 Signed-off-by: Marc Duiker <4191277+marcduiker@users.noreply.github.com> --- tests/cli/test_main.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tests/cli/test_main.py b/tests/cli/test_main.py index cdce0c33..ca577e09 100644 --- a/tests/cli/test_main.py +++ b/tests/cli/test_main.py @@ -155,7 +155,7 @@ def test_cli_send_is_blocking_and_capped(monkeypatch: pytest.MonkeyPatch) -> Non elapsed = time.monotonic() - start finally: server.close() - assert elapsed < 3.0 + assert elapsed < 1.5 # the hard cap, not per socket operation assert elapsed >= 0.5 # it really waited on the socket, not skipped the send From a4f66c6de70226976221f3dd9891edc0fd1d7cb0 Mon Sep 17 00:00:00 2001 From: Marc Duiker <4191277+marcduiker@users.noreply.github.com> Date: Wed, 25 Nov 2026 09:16:13 +0100 Subject: [PATCH 9/9] feat(cli): print a one-time telemetry notice before diagridpy first reports Co-Authored-By: Claude Opus 5.5 --- README.md | 2 + diagrid/cli/main.py | 9 +- diagrid/cli/telemetry_notice.py | 59 +++++++++++ tests/cli/conftest.py | 18 ++++ tests/cli/test_telemetry_notice.py | 163 +++++++++++++++++++++++++++++ 5 files changed, 250 insertions(+), 1 deletion(-) create mode 100644 diagrid/cli/telemetry_notice.py create mode 100644 tests/cli/conftest.py create mode 100644 tests/cli/test_telemetry_notice.py diff --git a/README.md b/README.md index fd3ae4c7..cc9e793f 100644 --- a/README.md +++ b/README.md @@ -68,6 +68,8 @@ Every agent runner reports one event when it is constructed, once per package pe `diagridpy`, the console script for `diagrid-cli`, reports to Reo only. It sends one event per invocation, including `--help` and `--version`. The send blocks the command for at most about one second in total, a hard cap that includes DNS resolution. A send still running at the cap is abandoned. Shell completion requests are not reported. +The first time `diagridpy` is about to report, it prints a short notice to stderr that names the opt-out variables, and records that it did in `~/.diagrid/telemetry-notice-shown` (or under `$DIAGRID_HOME` when set). Delete that file to see the notice again. Nothing is printed when reporting is skipped. + **What is sent:** the package name and version, the `diagrid-core` version, operating system, architecture, Python version, and, for agent runners, the agent framework and the installed version of its library. Nothing else: no prompts, application data, configuration, app IDs, hostnames, or file paths. | | Scarf | Reo | diff --git a/diagrid/cli/main.py b/diagrid/cli/main.py index 920c0853..27ca0462 100644 --- a/diagrid/cli/main.py +++ b/diagrid/cli/main.py @@ -12,6 +12,7 @@ import click +from diagrid.cli import telemetry_notice from diagrid.cli.commands.chaos import chaos from diagrid.cli.commands.deploy import deploy from diagrid.cli.commands.init import init @@ -48,10 +49,16 @@ def _is_completion_request(prog_name: str | None, complete_var: str | None) -> b def _report_cli_usage() -> None: - """Report one anonymous usage event to Reo. Never raises, never prints.""" + """Report one anonymous usage event to Reo. Never raises. + + The first run that is about to send prints a one-time notice to stderr + first; nothing else is ever printed. + """ if analytics is None: return try: + if analytics.REO_SINK.configured() and analytics.reo_allowed(): + telemetry_notice.show_notice_once() analytics.report_usage_blocking("diagrid-cli", sinks=(analytics.REO_SINK,)) except Exception: logging.getLogger(__name__).debug("cli usage report failed", exc_info=True) diff --git a/diagrid/cli/telemetry_notice.py b/diagrid/cli/telemetry_notice.py new file mode 100644 index 00000000..e657ec81 --- /dev/null +++ b/diagrid/cli/telemetry_notice.py @@ -0,0 +1,59 @@ +# Copyright (c) 2026-Present Diagrid Inc. +# SPDX-License-Identifier: BUSL-1.1 + +"""The one-time notice ``diagridpy`` prints before it first reports usage. + +Usage reporting is opt-out, so a CLI user who never reads the README would +otherwise not know it happens. The first run that is about to send an event +prints this notice to stderr and records that in a marker file, the way +``dotnet``, Homebrew and the Azure CLI do. +""" + +from __future__ import annotations + +import logging +import os +from pathlib import Path + +import click + +NOTICE = ( + "diagridpy sends anonymous usage data to Diagrid (Reo): package version, " + "OS, architecture and Python version.\n" + "To turn it off, set DO_NOT_TRACK=1 or DIAGRID_NO_ANALYTICS=1. Details: " + "https://github.com/diagridio/python-ai#usage-analytics\n" + "\n" +) + +MARKER_NAME = "telemetry-notice-shown" + + +def marker_path() -> Path: + """Return the marker file path, resolved now rather than at import. + + Same rule as ``diagrid.core.config.constants.DIAGRID_DIR``: ``$DIAGRID_HOME`` + when set, else ``~/.diagrid``. That constant is computed at import, so it + would miss a ``DIAGRID_HOME`` set afterwards. + """ + home = os.environ.get("DIAGRID_HOME") + base = Path(home) if home else Path.home() / ".diagrid" + return base / MARKER_NAME + + +def show_notice_once() -> None: + """Print the notice to stderr unless it was shown before. Never raises. + + The marker is written after printing. If it can't be written, the notice + shows again on the next run, which is accepted. + """ + try: + marker = marker_path() + if marker.exists(): + return + click.echo(NOTICE, err=True, nl=False) + marker.parent.mkdir(parents=True, exist_ok=True) + marker.touch() + except Exception: + logging.getLogger(__name__).debug( + "telemetry notice marker could not be written", exc_info=True + ) diff --git a/tests/cli/conftest.py b/tests/cli/conftest.py new file mode 100644 index 00000000..68293d87 --- /dev/null +++ b/tests/cli/conftest.py @@ -0,0 +1,18 @@ +# Copyright (c) 2026-Present Diagrid Inc. +# SPDX-License-Identifier: BUSL-1.1 + +from pathlib import Path + +import pytest + + +@pytest.fixture(autouse=True) +def _isolated_diagrid_home(monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> None: + """Keep the telemetry notice marker out of the developer's real home. + + ``diagridpy`` writes ``telemetry-notice-shown`` under ``$DIAGRID_HOME`` (or + ``~/.diagrid``) the first time it reports. Pointing ``DIAGRID_HOME`` at a + per-test directory means no CLI test touches the real one, and every test + starts as a first run. + """ + monkeypatch.setenv("DIAGRID_HOME", str(tmp_path / "diagrid-home")) diff --git a/tests/cli/test_telemetry_notice.py b/tests/cli/test_telemetry_notice.py new file mode 100644 index 00000000..8165d2d1 --- /dev/null +++ b/tests/cli/test_telemetry_notice.py @@ -0,0 +1,163 @@ +# Copyright (c) 2026-Present Diagrid Inc. +# SPDX-License-Identifier: BUSL-1.1 + +"""The one-time telemetry notice ``diagridpy`` prints before it first reports.""" + +from __future__ import annotations + +from pathlib import Path +from typing import Any + +import click +import pytest +from click.testing import CliRunner + +from diagrid.cli import telemetry_notice +from diagrid.cli.main import cli +from diagrid.core import analytics + +REO_TEST_ENDPOINT = "https://example.invalid/data" + +_GATE_ENV_VARS = ( + *analytics.OPT_OUT_ENV_VARS, + *analytics._CI_TRUTHY_ENV_VARS, + *analytics._CI_PRESENCE_ENV_VARS, + *analytics._DAPR_ENDPOINT_ENV_VARS, + "DAPR_API_TOKEN", + "KUBERNETES_SERVICE_HOST", +) + + +class _Response: + def __enter__(self) -> "_Response": + return self + + def __exit__(self, *_: Any) -> None: + return None + + +@pytest.fixture +def recorded(monkeypatch: pytest.MonkeyPatch) -> list[str]: + """Open the Reo gate and record each request instead of sending it.""" + for name in _GATE_ENV_VARS: + monkeypatch.delenv(name, raising=False) + monkeypatch.setattr(analytics, "REO_ENDPOINT", REO_TEST_ENDPOINT) + urls: list[str] = [] + + def fake_urlopen(request: Any, timeout: float = 0) -> _Response: + urls.append(request.full_url) + return _Response() + + monkeypatch.setattr(analytics.urllib.request, "urlopen", fake_urlopen) + return urls + + +def test_first_reporting_run_prints_notice_to_stderr(recorded: list[str]) -> None: + result = CliRunner().invoke(cli, ["--help"]) + assert result.exit_code == 0, result.output + assert telemetry_notice.NOTICE in result.stderr + assert telemetry_notice.NOTICE not in result.stdout + assert telemetry_notice.marker_path().exists() + assert len(recorded) == 1 + + +def test_second_run_prints_no_notice_but_still_reports( + monkeypatch: pytest.MonkeyPatch, recorded: list[str] +) -> None: + CliRunner().invoke(cli, ["--help"]) + monkeypatch.setattr(analytics, "_reported_packages", set()) + second = CliRunner().invoke(cli, ["--help"]) + assert second.exit_code == 0, second.output + assert telemetry_notice.NOTICE not in second.stderr + assert len(recorded) == 2 + + +def test_notice_is_shown_before_the_event_is_sent( + monkeypatch: pytest.MonkeyPatch, recorded: list[str] +) -> None: + order: list[str] = [] + real_echo = click.echo + + def tracking_echo(message: Any = None, *args: Any, **kwargs: Any) -> None: + if message == telemetry_notice.NOTICE: + order.append("notice") + real_echo(message, *args, **kwargs) + + def tracking_urlopen(request: Any, timeout: float = 0) -> _Response: + order.append("send") + return _Response() + + monkeypatch.setattr(telemetry_notice.click, "echo", tracking_echo) + monkeypatch.setattr(analytics.urllib.request, "urlopen", tracking_urlopen) + CliRunner().invoke(cli, ["--help"]) + assert order == ["notice", "send"] + + +@pytest.mark.parametrize( + ("name", "value"), + [("DO_NOT_TRACK", "1"), ("DIAGRID_NO_ANALYTICS", "1"), ("CI", "true")], +) +def test_no_notice_and_no_marker_when_nothing_is_sent( + monkeypatch: pytest.MonkeyPatch, recorded: list[str], name: str, value: str +) -> None: + monkeypatch.setenv(name, value) + result = CliRunner().invoke(cli, ["--help"]) + assert result.exit_code == 0, result.output + assert telemetry_notice.NOTICE not in result.stderr + assert not telemetry_notice.marker_path().exists() + assert recorded == [] + + +def test_no_notice_and_no_marker_without_an_endpoint( + monkeypatch: pytest.MonkeyPatch, recorded: list[str] +) -> None: + monkeypatch.setattr(analytics, "REO_ENDPOINT", "") + result = CliRunner().invoke(cli, ["--help"]) + assert telemetry_notice.NOTICE not in result.stderr + assert not telemetry_notice.marker_path().exists() + + +def test_no_notice_for_shell_completion( + monkeypatch: pytest.MonkeyPatch, recorded: list[str] +) -> None: + monkeypatch.setenv("_DIAGRIDPY_COMPLETE", "zsh_source") + CliRunner().invoke(cli, [], prog_name="diagridpy") + assert not telemetry_notice.marker_path().exists() + + +def test_unwritable_diagrid_home_does_not_break_the_command( + monkeypatch: pytest.MonkeyPatch, recorded: list[str], tmp_path: Path +) -> None: + blocker = tmp_path / "a-file" + blocker.write_text("x") + monkeypatch.setenv("DIAGRID_HOME", str(blocker / "sub")) + result = CliRunner().invoke(cli, ["--version"]) + assert result.exit_code == 0, result.output + assert "diagridpy" in result.stdout + assert len(recorded) == 1 + + +def test_marker_path_follows_diagrid_home_at_call_time( + monkeypatch: pytest.MonkeyPatch, tmp_path: Path +) -> None: + monkeypatch.setenv("DIAGRID_HOME", str(tmp_path / "a")) + assert telemetry_notice.marker_path() == tmp_path / "a" / "telemetry-notice-shown" + + +def test_marker_path_defaults_to_dot_diagrid_in_home( + monkeypatch: pytest.MonkeyPatch, tmp_path: Path +) -> None: + monkeypatch.delenv("DIAGRID_HOME", raising=False) + monkeypatch.setattr(Path, "home", lambda: tmp_path / "fake-home") + assert ( + telemetry_notice.marker_path() + == tmp_path / "fake-home" / ".diagrid" / "telemetry-notice-shown" + ) + + +def test_cli_tests_never_touch_the_real_home( + monkeypatch: pytest.MonkeyPatch, recorded: list[str], tmp_path: Path +) -> None: + monkeypatch.setattr(Path, "home", lambda: tmp_path / "fake-home") + CliRunner().invoke(cli, ["--help"]) + assert not (tmp_path / "fake-home" / ".diagrid").exists()