Skip to content
Open
29 changes: 25 additions & 4 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -62,13 +62,34 @@ 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 in total, a hard cap that includes DNS resolution. A send still running at the cap is abandoned. Shell completion requests are not reported.

To opt out, set any of these environment variables before starting your application:
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 |
|---|---|---|
| Sent by | agent runners | agent runners and `diagridpy` |
| 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.

**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
Expand Down
12 changes: 9 additions & 3 deletions diagrid/agent/core/workflow/runner.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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

def report_usage(package: str, **dimensions: object) -> None:
# ``sinks`` is accepted and ignored: an older core has no destination list.
def report_usage(
package: str, *, sinks: Sequence["Sink"] = (), **dimensions: object

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

nit: the runner never passes sinks (it calls report_usage("diagrid", kind=..., ...)), so the fallback doesn't need the new parameter, the TYPE_CHECKING import of Sink or the Sequence import. The old **dimensions signature still matches every call site.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I tried that, but mypy rejects it: runner.py:30: error: All conditional function variants must have identical signatures [misc]. The real report_usage now takes the sinks keyword, so the fallback has to match it even though the runner never passes it. I've left it as it is.

) -> None:
return None


Expand Down
73 changes: 72 additions & 1 deletion diagrid/cli/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,16 +5,87 @@

from __future__ import annotations

import logging
import os
import sys
from typing import Any

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
from diagrid.cli.utils.process import set_verbose
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.

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,))

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This makes diagridpy report on every run, including --help and --version, and it blocks for up to a second. The README covers it, but a CLI user who never reads the README sees nothing. What do you think about printing a one-time notice to stderr on first run that names the opt-out variables (DO_NOT_TRACK, DIAGRID_NO_ANALYTICS)? It could be recorded with a marker file under the user's config dir, the way dotnet, Homebrew and the Azure CLI handle telemetry. It's a small change, and it saves the first person who notices the outbound request from opening an issue about it. Not blocking.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Added in a4f66c6. The first time diagridpy is about to send an event, it prints a two-line notice to stderr that names DO_NOT_TRACK and DIAGRID_NO_ANALYTICS. Then it writes ~/.diagrid/telemetry-notice-shown (or the same file under $DIAGRID_HOME), so the notice only shows once. When reporting is skipped (opted out, CI, Kubernetes, a Catalyst target, shell completion) it prints nothing and writes no marker. If the marker can't be written, the command still exits normally and the notice shows again on the next run. I added a line about it to the README too.

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 = 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()
@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.
Expand Down
59 changes: 59 additions & 0 deletions diagrid/cli/telemetry_notice.py
Original file line number Diff line number Diff line change
@@ -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
)
Loading