From b37c04639c133d8e1343451721ae996e01f57eb3 Mon Sep 17 00:00:00 2001 From: Nick DeJesus Date: Thu, 3 Dec 2026 15:02:19 -0500 Subject: [PATCH] feat(telemetry): send error reports again, to a new Sentry project dg has sent no telemetry since 0.4.1. This turns error reporting back on: one report per run, only for an unexpected error, built from the published field allowlist, sent to the `deepgram-cli` Sentry project. - The destination is built in. DEEPCTL_TELEMETRY_DSN can only replace it with a loopback sink; any other value, an empty one included, turns reporting off. - A source checkout never reports. dg reads its own install metadata: the metadata must come from an installer, describe the code that is running, and not be an editable install. - Nothing is sent before dg has said so. The first run at a terminal prints a one-time notice on stderr and sends nothing; reports start with the next run. A local sink and DEEPCTL_TELEMETRY=log don't wait for it. - A plugin command's path and flag names are left out of a report, like a plugin's module and function names already were. - Every existing opt-out still applies: --no-telemetry, DEEPCTL_TELEMETRY_DISABLED, DEEPCTL_TELEMETRY=off, DO_NOT_TRACK, CI and telemetry.enabled: false in the user config. Refs #179 Co-Authored-By: Claude Fable 5.2 --- README.md | 10 +- conftest.py | 6 +- docs/telemetry.md | 25 +- .../src/deepctl_core/base_command.py | 2 +- .../src/deepctl_core/config_models.py | 2 +- .../deepctl-core/src/deepctl_core/messages.py | 4 +- .../src/deepctl_core/telemetry_context.py | 26 +- packages/deepctl-core/tests/unit/test_base.py | 5 + packages/deepctl-telemetry/README.md | 2 +- packages/deepctl-telemetry/pyproject.toml | 2 +- .../src/deepctl_telemetry/__init__.py | 4 +- .../src/deepctl_telemetry/client.py | 163 ++++-- .../src/deepctl_telemetry/first_run.py | 95 ++++ .../src/deepctl_telemetry/notice.py | 13 +- .../tests/golden/notice_first_run.txt | 1 + .../tests/golden/readme_telemetry.md | 6 +- .../tests/unit/test_contract.py | 6 +- .../tests/unit/test_envelopes.py | 28 +- .../tests/unit/test_telemetry.py | 510 ++++++++++++++++-- src/deepctl/_cache.py | 4 +- src/deepctl/_cli.py | 22 +- tests/unit/test_cache.py | 4 +- tests/unit/test_telemetry_wiring.py | 171 +++++- 23 files changed, 980 insertions(+), 131 deletions(-) create mode 100644 packages/deepctl-telemetry/src/deepctl_telemetry/first_run.py create mode 100644 packages/deepctl-telemetry/tests/golden/notice_first_run.txt diff --git a/README.md b/README.md index 45b1d244..39516b79 100644 --- a/README.md +++ b/README.md @@ -505,9 +505,11 @@ flag: `dg --output json `. `dg speak --output FILE` writes audio to ## Telemetry -This version of dg sends no telemetry: no error reports, usage data or other telemetry, whether a command succeeds or fails. dg still contacts the Deepgram API for the commands you run, and pypi.org to check for updates. +When a command fails with an unexpected error, dg sends one error report to Deepgram's Sentry project. Nothing is sent when a command succeeds, `--help` and `--version` included, or for a usage error or another error dg reports to you. Nothing is sent either until dg has told you about this: the first run at a terminal prints a one-time notice, and reports start with the run after it. -The `DEEPCTL_TELEMETRY_DISABLED` environment variable and the `telemetry.enabled` setting in `config.yaml` are still accepted, and the new `--no-telemetry` flag is accepted too, but none of them has an effect in this version. `DEEPCTL_TELEMETRY_DSN` is now ignored unless it points at the local machine, which is for tests. The last line of `dg --help` says that dg sends no telemetry. +A report holds the exception type, the module, function and line number of each stack frame, the command path, the names of the flags used, and the dg version, operating system, CPU architecture and Python version. It never holds flag values or arguments, file names or paths, environment variables, API keys, request or response data, error messages, log output, variable values, your hostname or your username. [docs/telemetry.md](docs/telemetry.md) lists every field. + +To turn it off, pass `--no-telemetry` for one command, set `DEEPCTL_TELEMETRY_DISABLED=1` or `DO_NOT_TRACK=1`, or put `telemetry.enabled: false` in your `config.yaml`. It is off whenever `CI` is set. To see a report instead of sending it, run a command with `DEEPCTL_TELEMETRY=log`. The last line of `dg --help` says whether telemetry is on. ## Development @@ -554,7 +556,7 @@ cli/ │ ├── deepctl-core/ # Core components for deepctl │ ├── deepctl-plugin-example/ # Example plugin for deepctl │ ├── deepctl-shared-utils/ # Shared utilities for deepctl -│ └── deepctl-telemetry/ # Error reporting for deepctl; this version sends no telemetry +│ └── deepctl-telemetry/ # Error reporting for deepctl: unexpected errors only, allowlisted fields ├── tests/ # Integration tests └── Makefile # Development tasks ``` @@ -630,7 +632,7 @@ cli/ | [`deepctl-core`](packages/deepctl-core) | Core components for deepctl | | [`deepctl-plugin-example`](packages/deepctl-plugin-example) | Example plugin for deepctl | | [`deepctl-shared-utils`](packages/deepctl-shared-utils) | Shared utilities for deepctl | -| [`deepctl-telemetry`](packages/deepctl-telemetry) | Error reporting for deepctl; this version sends no telemetry | +| [`deepctl-telemetry`](packages/deepctl-telemetry) | Error reporting for deepctl: unexpected errors only, allowlisted fields | ## Release diff --git a/conftest.py b/conftest.py index 7abf788b..7244e5fe 100644 --- a/conftest.py +++ b/conftest.py @@ -65,7 +65,11 @@ def _disable_telemetry(monkeypatch): """Keep tests that call `main()` from initializing real telemetry. The destination also points at a closed loopback port, so a test that - re-enables telemetry can never reach a real endpoint. + re-enables telemetry can never reach a real endpoint. Without that + variable an editable install has no destination, but a suite run against + built wheels would report to dg's Sentry project (once the first-run + notice has been shown on this machine): a test that removes it must + patch the SDK, and one that starts a child process must pass it on. """ monkeypatch.setenv("DEEPCTL_TELEMETRY_DISABLED", "1") monkeypatch.setenv("DEEPCTL_TELEMETRY_DSN", "http://k@127.0.0.1:9/1") diff --git a/docs/telemetry.md b/docs/telemetry.md index 577847d8..31001d78 100644 --- a/docs/telemetry.md +++ b/docs/telemetry.md @@ -1,19 +1,20 @@ # Telemetry -This version of dg sends no telemetry: no error reports, usage data or other telemetry, whether a command succeeds or fails. It has no built-in destination for reports. dg still contacts the Deepgram API for the commands you run, and pypi.org to check for updates. +When a command fails with an unexpected error, dg sends one error report to Deepgram's Sentry project (`deepgram-cli`). That is all the telemetry dg has: it sends no usage data, and nothing at all when a command succeeds. dg also contacts the Deepgram API for the commands you run, and pypi.org to check for updates. -The error-reporting code is still in dg, and it runs only when `DEEPCTL_TELEMETRY_DSN` points at a sink on this machine (a loopback address such as `127.0.0.1`), which is for tests and local development. A value that points anywhere else is ignored. This page describes what that code does with a loopback sink: when it runs, the switches that turn it off, and the exact fields of a report. +Reporting is on by default, and dg tells you so once before it sends anything. This page describes when a report is sent, the switches that turn reporting off, and the exact fields of a report. The last line of `dg --help` says whether it is on. ## When it runs -- **Only with a loopback `DEEPCTL_TELEMETRY_DSN`.** Without one, dg installs no error hooks, never loads the reporting library, and the last line of `dg --help` says "This version of dg sends no telemetry." -- **At most one report per run**, and only for an unexpected error. Nothing is reported when a command succeeds, for a usage error or another error dg reports to you, or for `--help` and `--version`. +- **Not before dg has told you.** The first time you run a command at a terminal, dg prints a one-time notice on stderr that says reporting is on and how to turn it off. That run sends nothing, and neither does any run before it; reports start with the next run. The notice isn't printed under `--quiet`, for `--help`, or when dg isn't run by a person at a terminal (a script, a container, an AI agent session), so an install that is only ever used that way never sends a report. +- **At most one report per run**, and only for an unexpected error. Nothing is reported when a command succeeds, `--help` and `--version` included, or for a usage error or another error dg reports to you. - **No network or reporting code on the success path.** The reporting library is loaded only after an unexpected error, so a command that succeeds opens no connection for telemetry. - **A short time budget.** dg waits about 0.6 s at most for a report, loading included, and doesn't wait at all when no report was queued. +- **No proxy.** A report goes straight to Sentry and doesn't use a proxy from your environment or system settings. If Sentry can't be reached that way, the report is dropped. ## Turn it off -With a loopback sink set, any one of these turns reporting off. They are checked in this order: +Any one of these turns reporting off. They are checked in this order: | Switch | Scope | |---|---| @@ -26,17 +27,21 @@ With a loopback sink set, any one of these turns reporting off. They are checked For `DEEPCTL_TELEMETRY_DISABLED`, `DO_NOT_TRACK` and `CI`, any value except an empty one, `0`, `false`, `no` or `off` turns reporting off. `DEEPCTL_TELEMETRY` turns it off when set to `off`, `0`, `false`, `no` or `disabled`; `log` is described below, and any other value changes nothing. A config file dg won't load (unreadable, too large, not valid YAML, a repeated `telemetry` key, or one dg doesn't trust in an AI agent session) counts as turned off too. A project's `deepgram.yaml` can't change these settings. +Reporting is also off when dg runs from a source checkout (an editable install, such as `uv sync` or `pip install -e .`). dg reads that from its own install metadata, so there is nothing to set. + +`DEEPCTL_TELEMETRY_DSN` is for tests and local development. Set to a sink on this machine (a loopback address such as `127.0.0.1`), it replaces Sentry as the destination. Set to anything else, an empty value included, it turns reporting off; it can't send reports to another host. A local sink doesn't wait for the first-run notice, since nothing leaves your machine. + ## See a report -With a loopback sink set, run a command with `DEEPCTL_TELEMETRY=log`. If it fails with an unexpected error and reporting is on, dg prints the report to stderr as one JSON line and sends nothing, not even to the loopback sink. +Run a command with `DEEPCTL_TELEMETRY=log`. If it fails with an unexpected error and reporting is on, dg prints the report to stderr as one JSON line and sends nothing. This works before the first-run notice has been shown too. ```sh -DEEPCTL_TELEMETRY_DSN=http://key@127.0.0.1:9000/1 DEEPCTL_TELEMETRY=log dg listen recording.wav +DEEPCTL_TELEMETRY=log dg listen recording.wav ``` ## Field schema -A report holds these fields and nothing else. A value that doesn't match its expected shape (an identifier, a version string, a command path) is dropped, never shortened or escaped. Names from code outside dg and the libraries it calls, such as a plugin's, are sent as ``. +A report holds these fields and nothing else. A value that doesn't match its expected shape (an identifier, a version string, a command path) is dropped, never shortened or escaped. Names from code outside dg and the libraries it calls, such as a plugin's, are sent as ``, and a plugin command's path and flag names are left out. | Field | Contents | @@ -49,8 +54,8 @@ A report holds these fields and nothing else. A value that doesn't match its exp | `environment` | Always `production` | | `sdk.name` | Name of the reporting library | | `sdk.version` | Version of the reporting library | -| `tags.cmd.path` | Command path, such as `dg listen` | -| `tags.cmd.flags` | Names of the flags used, never their values, such as `--model,--output` | +| `tags.cmd.path` | Command path, such as `dg listen` (dg's own commands only) | +| `tags.cmd.flags` | Names of the flags used, never their values, such as `--model,--output` (dg's own commands only) | | `tags.cli.os` | Operating system, such as `Darwin` | | `tags.cli.arch` | CPU architecture, such as `arm64` | | `tags.cli.python` | Python version, such as `3.12.4` | diff --git a/packages/deepctl-core/src/deepctl_core/base_command.py b/packages/deepctl-core/src/deepctl_core/base_command.py index c12ddbe1..50e01853 100644 --- a/packages/deepctl-core/src/deepctl_core/base_command.py +++ b/packages/deepctl-core/src/deepctl_core/base_command.py @@ -428,7 +428,7 @@ def _record_telemetry_context(self, ctx: click.Context) -> None: try: from .telemetry_context import record_command - record_command(ctx) + record_command(ctx, type(self).__module__) except Exception: pass diff --git a/packages/deepctl-core/src/deepctl_core/config_models.py b/packages/deepctl-core/src/deepctl_core/config_models.py index 9ebb2a39..a8356821 100644 --- a/packages/deepctl-core/src/deepctl_core/config_models.py +++ b/packages/deepctl-core/src/deepctl_core/config_models.py @@ -58,7 +58,7 @@ class ToolsConfig(BaseModel): class TelemetryConfig(BaseModel): - """Telemetry setting, still accepted. This version sends no telemetry.""" + """Error-report setting. Read from the user config file only.""" enabled: bool = True diff --git a/packages/deepctl-core/src/deepctl_core/messages.py b/packages/deepctl-core/src/deepctl_core/messages.py index ad14e238..26c8dfbb 100644 --- a/packages/deepctl-core/src/deepctl_core/messages.py +++ b/packages/deepctl-core/src/deepctl_core/messages.py @@ -302,8 +302,8 @@ ), "W-PF-TELEMETRY": ( "project files can't change telemetry settings.", - "This version of dg sends no telemetry.", - None, + "Set them in {user_config}.", + AGENT_SETTINGS_HINT, ), "W-PF-UPDATE": ( "project files can't change update settings.", diff --git a/packages/deepctl-core/src/deepctl_core/telemetry_context.py b/packages/deepctl-core/src/deepctl_core/telemetry_context.py index 639ebfac..9a1ede1b 100644 --- a/packages/deepctl-core/src/deepctl_core/telemetry_context.py +++ b/packages/deepctl-core/src/deepctl_core/telemetry_context.py @@ -4,9 +4,10 @@ has already loaded. Commands record their context here on every run, and the telemetry client reads it only if an error is reported. -Only the command path and the *names* of flags the user passed are kept. -Flag values, positional arguments and the program name from argv are never -recorded. +Only the command path and the *names* of flags the user passed are kept, +with the module that defines the command, so telemetry can leave out the +path and flags of a command that isn't one of dg's own. Flag values, +positional arguments and the program name from argv are never recorded. """ from __future__ import annotations @@ -18,6 +19,7 @@ # Names that look like identifiers. Anything else is dropped rather than # escaped, so a crafted command or option name can't smuggle data out. _TOKEN_RE = re.compile(r"^-{0,2}[A-Za-z][A-Za-z0-9_-]{0,63}$") +_MODULE_RE = re.compile(r"^[A-Za-z_][A-Za-z0-9_.]{0,127}$") # Replaced as a whole on each record, never mutated, so a reader on another # thread sees either the old or the new context, not a mix. @@ -28,8 +30,16 @@ def _safe(token: str) -> str | None: return token if _TOKEN_RE.match(token) else None -def record_command(ctx: click.Context) -> None: - """Record the command path and user-supplied flag names for this run.""" +def _safe_module(module: str) -> str: + return module if _MODULE_RE.match(module) else "" + + +def record_command(ctx: click.Context, module: str) -> None: + """Record the command path and user-supplied flag names for this run. + + `module` is the module of the command class. Telemetry sends the path + and flags only when it is one of dg's own packages. + """ chain: list[click.Context] = [] node: click.Context | None = ctx while node is not None: @@ -58,7 +68,11 @@ def record_command(ctx: click.Context) -> None: flags.add(flag) global _context - _context = {"command": " ".join(parts), "flags": ",".join(sorted(flags))} + _context = { + "command": " ".join(parts), + "flags": ",".join(sorted(flags)), + "module": _safe_module(module), + } def command_context() -> dict[str, str]: diff --git a/packages/deepctl-core/tests/unit/test_base.py b/packages/deepctl-core/tests/unit/test_base.py index 0c83d77c..9e2cc4c0 100644 --- a/packages/deepctl-core/tests/unit/test_base.py +++ b/packages/deepctl-core/tests/unit/test_base.py @@ -1495,6 +1495,11 @@ def test_records_flag_names_from_every_level_but_no_values(self): def test_no_flags_records_empty(self): assert self._invoke(["listen"])["flags"] == "" + @pytest.mark.unit + def test_records_the_module_that_defines_the_command(self): + # Telemetry sends the path and flags only for dg's own packages. + assert self._invoke(["listen"])["module"] == __name__ + @pytest.mark.unit def test_record_swallows_exceptions(self): class MockCommand(BaseCommand): diff --git a/packages/deepctl-telemetry/README.md b/packages/deepctl-telemetry/README.md index 5162efab..55e6ef8d 100644 --- a/packages/deepctl-telemetry/README.md +++ b/packages/deepctl-telemetry/README.md @@ -2,7 +2,7 @@ > Part of [deepctl](https://github.com/deepgram/cli) — Official Deepgram CLI -Error reporting for deepctl; this version sends no telemetry +Error reporting for deepctl: unexpected errors only, allowlisted fields This package provides internal APIs for deepctl and its command packages. It is not intended for direct use. diff --git a/packages/deepctl-telemetry/pyproject.toml b/packages/deepctl-telemetry/pyproject.toml index 1dac9dff..1d1b9c6a 100644 --- a/packages/deepctl-telemetry/pyproject.toml +++ b/packages/deepctl-telemetry/pyproject.toml @@ -5,7 +5,7 @@ build-backend = "setuptools.build_meta" [project] name = "deepctl-telemetry" version = "0.5.0" # x-release-please-version -description = "Error reporting for deepctl; this version sends no telemetry" +description = "Error reporting for deepctl: unexpected errors only, allowlisted fields" readme = "README.md" license = "MIT" authors = [{ name = "Deepgram", email = "devrel@deepgram.com" }] diff --git a/packages/deepctl-telemetry/src/deepctl_telemetry/__init__.py b/packages/deepctl-telemetry/src/deepctl_telemetry/__init__.py index 22439474..06242f3e 100644 --- a/packages/deepctl-telemetry/src/deepctl_telemetry/__init__.py +++ b/packages/deepctl-telemetry/src/deepctl_telemetry/__init__.py @@ -1,9 +1,11 @@ -"""Error reporting for deepctl. This version sends no telemetry.""" +"""Error reporting for deepctl: unexpected errors only, allowlisted fields.""" from .client import disable_for_run, init_telemetry, is_enabled, report_exception +from .first_run import claim_first_run_notice from .notice import install_help_notice, render_notice __all__ = [ + "claim_first_run_notice", "disable_for_run", "init_telemetry", "install_help_notice", diff --git a/packages/deepctl-telemetry/src/deepctl_telemetry/client.py b/packages/deepctl-telemetry/src/deepctl_telemetry/client.py index 5420c70e..0c50bf35 100644 --- a/packages/deepctl-telemetry/src/deepctl_telemetry/client.py +++ b/packages/deepctl-telemetry/src/deepctl_telemetry/client.py @@ -1,9 +1,13 @@ """Sentry-backed telemetry client: unexpected errors only, allowlisted fields. -This version has no built-in destination, so it sends no telemetry. A -report can go only to a DEEPCTL_TELEMETRY_DSN override on a loopback -address, which exists for tests and local sinks. Without one, telemetry is -off: no hooks are installed and the SDK is never imported. +Reports go to the built-in destination, SENTRY_DSN, unless +DEEPCTL_TELEMETRY_DSN is set. That override exists for tests and local +sinks: a loopback address replaces the destination, and any other value +turns telemetry off, so it can never send reports to another host. Only a +released install uses the built-in destination: dg run from a source +checkout (an editable install) has none, so its errors are never reported. +And nothing goes to the built-in destination until a run after the one +that showed the first-run notice (see first_run.py). The SDK is never imported on the success path. ``init_telemetry`` only records the enabled decision and installs stdlib exception hooks; @@ -25,6 +29,8 @@ from pathlib import Path from typing import TYPE_CHECKING, Any +from .first_run import notice_shown + if TYPE_CHECKING: from types import TracebackType @@ -37,8 +43,14 @@ # ignored, and `--help` says this version of dg sends no telemetry. TELEMETRY_BUILD_ENABLED = True -# There is no built-in destination: _dsn() returns a DEEPCTL_TELEMETRY_DSN -# override on a loopback address, or None, and with None nothing is sent. +# The built-in destination: the `deepgram-cli` Sentry project. A DSN only +# lets a client submit events, and it ships in every install, so it is not a +# secret. Never point this at the `dx-cli` project that 0.2.21 to 0.4.0 +# reported to: that project is retired, and a test rejects its key and ID. +SENTRY_DSN = ( + "https://aec8f3dd040673b864c284fc1491755c" + "@o206115.ingest.us.sentry.io/4512538396459008" +) DSN_ENV_VAR = "DEEPCTL_TELEMETRY_DSN" DISABLE_ENV_VAR = "DEEPCTL_TELEMETRY_DISABLED" @@ -67,11 +79,13 @@ def _fresh_state() -> dict[str, Any]: """Per-run state, stdlib types only. - `opt_out` names the switch that turned telemetry off ("build", "dsn" - when there is no destination, "flag", "env", "do_not_track", "ci" or - "config"); `config_path` is the user config file the decision was read - from; `reported` is set once a report starts, `sent` once an event has - been handed to the transport. + `opt_out` names what turned telemetry off: "build", "source" (dg + runs from a source checkout), "dsn" (DEEPCTL_TELEMETRY_DSN isn't a + loopback address), "flag", "env", "do_not_track", "ci", "config", or + "notice" (the first-run notice hasn't been shown before this run). + `config_path` is the user config file the decision was read from; + `reported` is set once a report starts, `sent` once an event has been + handed to the transport. """ return { "enabled": False, @@ -210,7 +224,7 @@ def _opt_out_source(config: Config) -> str | None: if not TELEMETRY_BUILD_ENABLED: return "build" if _dsn() is None: - return "dsn" + return "dsn" if DSN_ENV_VAR in os.environ else "source" if _state["disabled_for_run"]: return "flag" if _env_opts_out(): @@ -221,18 +235,25 @@ def _opt_out_source(config: Config) -> str | None: return "ci" if _user_config_opts_out(config): return "config" + # Only a report that leaves this machine waits for the first-run notice: + # a loopback sink and log mode send nothing to Deepgram. + if DSN_ENV_VAR not in os.environ and not _log_mode() and not notice_shown(): + return "notice" return None def is_enabled(config: Config) -> bool: """Whether telemetry may report an error for this invocation. - Resolution order: the build switch, then whether there is a - destination (a loopback DEEPCTL_TELEMETRY_DSN; without one telemetry is - off), then `--no-telemetry` for this run, then the env overrides + Resolution order: the build switch, then the destination (running + from a source checkout turns telemetry off, and so does a + DEEPCTL_TELEMETRY_DSN that isn't a loopback address), then + `--no-telemetry` for this run, then the env overrides (DEEPCTL_TELEMETRY_DISABLED or DEEPCTL_TELEMETRY set to off, DO_NOT_TRACK, CI), then `telemetry.enabled` in the user's config file - (default on). The project's `deepgram.yaml` is never read. + (default on), then the first-run notice: nothing is sent to the + built-in destination until an earlier run has shown it. The project's + `deepgram.yaml` is never read. """ return _opt_out_source(config) is None @@ -306,16 +327,70 @@ def _reportable(exc: BaseException | None) -> BaseException | None: return exc if isinstance(exc, Exception) else None -def _dsn() -> str | None: - """A DEEPCTL_TELEMETRY_DSN override on loopback, or None. +def _released_install() -> bool: + """Whether this dg is an installed release, not a source checkout. - There is no built-in DSN, so without an override there is nowhere to - send a report. The override exists for tests and local sinks, so a - non-loopback value is ignored rather than allowed to redirect reports. + Read from the install's own metadata, so it doesn't depend on an + environment variable. Three things must hold: + + - deepctl's metadata was written by an installer: it has a `WHEEL` + file. The `deepctl.egg-info` a build leaves in the source tree has + none, and that is the metadata Python finds when the tree is on + PYTHONPATH. + - The `deepctl` package that is running is the copy that metadata + describes, not a source tree placed ahead of it on the path. + - The install isn't editable. An editable install (`uv sync`, + `pip install -e .`) records `"dir_info": {"editable": true}` in + `direct_url.json` (PEP 610). An install from an index has no such + file, and one from a wheel, an archive or a plain directory build + (as Homebrew does) has one that doesn't say editable. + + False when any of it can't be read. """ - override = os.environ.get(DSN_ENV_VAR, "").strip() - if not override: - return None + try: + import importlib.metadata + import importlib.util + import json + + dist = importlib.metadata.distribution("deepctl") + if dist.read_text("WHEEL") is None: + return False + spec = importlib.util.find_spec("deepctl") + installed = dist.locate_file("deepctl/__init__.py") + if spec is None or spec.origin is None: + return False + if not os.path.samefile(spec.origin, str(installed)): + return False + raw = dist.read_text("direct_url.json") + if raw is None: + return True + info = json.loads(raw) + except Exception: + return False + if not isinstance(info, dict): + return False + dir_info = info.get("dir_info") + return not (isinstance(dir_info, dict) and dir_info.get("editable") is True) + + +def _dsn() -> str | None: + """Where a report goes: SENTRY_DSN, a loopback override, or None. + + Without an override, a released install reports to SENTRY_DSN and a + source checkout has no destination, so work in progress is never + reported as a release (see `_released_install`). + + DEEPCTL_TELEMETRY_DSN exists for tests and local sinks. Set to a + loopback address it replaces the built-in destination. Set to anything + else, an empty value included, it yields None, which turns telemetry + off: the override can't redirect reports to another host, and it never + falls back to the built-in destination, so a test run that sets it + can't reach Sentry. + """ + override = os.environ.get(DSN_ENV_VAR) + if override is None: + return SENTRY_DSN if _released_install() else None + override = override.strip() try: import ipaddress from urllib.parse import urlsplit @@ -331,16 +406,15 @@ def _dsn() -> str | None: def report_exception(exc: BaseException | None) -> bool: """Send one error report for `exc` if telemetry is on. - Does nothing, and never imports the SDK, without a loopback - DEEPCTL_TELEMETRY_DSN. Imports and initializes the SDK only here. At - most one report per process. The flush waits at most - FLUSH_TIMEOUT_SECONDS after init, and the whole call is held to - REPORT_BUDGET_SECONDS (but the flush always gets FLUSH_FLOOR_SECONDS); - there is no flush when no event was queued. With DEEPCTL_TELEMETRY=log - the event is printed to stderr instead and nothing is sent, not even to - the loopback DSN. Never raises an Exception; a KeyboardInterrupt during - the flush propagates to the caller. Returns whether an event was handed - to the SDK. + Does nothing, and never imports the SDK, when telemetry is off. Imports + and initializes the SDK only here. At most one report per process. The + flush waits at most FLUSH_TIMEOUT_SECONDS after init, and the whole call + is held to REPORT_BUDGET_SECONDS (but the flush always gets + FLUSH_FLOOR_SECONDS); there is no flush when no event was queued. With + DEEPCTL_TELEMETRY=log the event is printed to stderr instead and nothing + is sent, to Sentry or to a loopback DSN. Never raises an Exception; a + KeyboardInterrupt during the flush propagates to the caller. Returns + whether an event was handed to the SDK. """ started = time.monotonic() with _report_lock: @@ -422,8 +496,9 @@ def _sdk_options(dsn: str | None, cli_version: str) -> dict[str, Any]: rule holds). No traces, profiles, sessions or logs, and no locals, source lines, stack snapshots or hostname. No proxy: an empty `http_proxy` and `https_proxy` stop the SDK from falling back to a proxy - from the environment or the system settings, so a report to a loopback - DSN stays on this machine. `before_send` and `before_send_transaction` + from the environment or the system settings, so a report goes straight + to its destination or not at all, and one to a loopback DSN stays on + this machine. `before_send` and `before_send_transaction` then rebuild whatever is left from the allowlist in `_rebuild_event`. """ return { @@ -547,8 +622,12 @@ def _is_broken_pipe(event: Event) -> bool: OTHER_NAME = "" +def _top_level(module: str) -> str: + return module.split(".", 1)[0] + + def _known_module(module: str) -> bool: - top = module.split(".", 1)[0] + top = _top_level(module) return ( top in _FIRST_PARTY or top in _KNOWN_PACKAGES @@ -570,7 +649,12 @@ def _match(pattern: re.Pattern[str], value: object) -> str | None: def _allowed_tags() -> dict[str, str]: - """Run-level fields: command path, flag names, version, OS, arch, Python.""" + """Run-level fields: command path, flag names, version, OS, arch, Python. + + The command path and flag names are sent only for a command defined in + one of dg's own packages. A plugin's command name and flag names are its + own identifiers, like its module and function names, and are left out. + """ try: from deepctl_core.telemetry_context import command_context @@ -578,6 +662,9 @@ def _allowed_tags() -> dict[str, str]: except ImportError: # An older deepctl-core without the context: report without cmd.*. context = {} + module = _match(_NAME_RE, context.get("module")) or "" + if _top_level(module) not in _FIRST_PARTY: + context = {} candidates = { "cmd.path": _match(_COMMAND_RE, context.get("command")), "cmd.flags": _match(_FLAGS_RE, context.get("flags")), diff --git a/packages/deepctl-telemetry/src/deepctl_telemetry/first_run.py b/packages/deepctl-telemetry/src/deepctl_telemetry/first_run.py new file mode 100644 index 00000000..b8821584 --- /dev/null +++ b/packages/deepctl-telemetry/src/deepctl_telemetry/first_run.py @@ -0,0 +1,95 @@ +"""The one-time notice that error reports are on. + +Reporting is on by default, so dg says so before it sends anything. The +first run at a terminal prints FIRST_RUN_NOTICE to stderr, and reports start +with the run after it: the run that shows the notice sends nothing, and +neither does any run before it. An install that is never run by a person at +a terminal (a container, a script, an AI agent session) never reports. + +"Shown" is an empty file, ``/telemetry/notice-shown``, in the cache +directory of the account's real home (``HOME`` and ``XDG_CACHE_HOME`` are +ignored, as for the help cache), so every session of one user reads the same +answer and a redirected home can't supply it. The directory and file follow +the cache's ownership rules (``deepctl._cache``). When the file can't be +read or written, the notice counts as not shown, and nothing is sent. +""" + +from __future__ import annotations + +import os +import sys + +# Golden text, compared byte for byte with tests/golden/notice_first_run.txt. +# It names the same opt-outs as the `--help` footer (notice.NOTICE_ON). +FIRST_RUN_NOTICE = ( + "From the next run on, dg reports unexpected errors to Deepgram, with no " + "flag values, paths or keys. Turn off: --no-telemetry, " + "DEEPCTL_TELEMETRY_DISABLED=1, or telemetry.enabled: false in " + "config.yaml. DO_NOT_TRACK=1 and CI turn it off too. This notice is " + "shown once." +) + +MARKER_DIR = "telemetry" +MARKER_FILE = "notice-shown" + + +def _marker(create: bool) -> str | None: + """The marker's path, or None when its directory is missing or unsafe.""" + from deepctl import _cache + + directory = _cache._private_dir(MARKER_DIR, create=create, real=True) + return None if directory is None else os.path.join(directory, MARKER_FILE) + + +def notice_shown() -> bool: + """Whether an earlier run showed the notice to this user.""" + try: + from deepctl import _cache + + path = _marker(create=False) + return path is not None and _cache._read_private(path) is not None + except Exception: + return False + + +def _record_shown() -> bool: + try: + from deepctl import _cache + + path = _marker(create=True) + if path is None: + return False + _cache._write_private(path, b"") + except Exception: + return False + return True + + +def _person_at_terminal() -> bool: + """stderr is a terminal, and this isn't an AI agent or automation.""" + try: + if sys.stderr is None or not sys.stderr.isatty(): + return False + from deepctl_core.output import is_agentic, is_ai_agent + except Exception: + return False + return not (is_agentic() or is_ai_agent()) + + +def claim_first_run_notice() -> str | None: + """The notice to print on stderr now, or None. + + Call after ``init_telemetry``, and print what it returns. It returns the + text only when the notice is all that keeps telemetry off for this run + (so not for someone who opted out, or in a source checkout), a person is + at the terminal, and the notice could be recorded as shown; it is + recorded before it is returned, so it is printed at most once. This run + still sends nothing. + """ + from . import client + + if client._state["opt_out"] != "notice" or notice_shown(): + return None + if not _person_at_terminal() or not _record_shown(): + return None + return FIRST_RUN_NOTICE diff --git a/packages/deepctl-telemetry/src/deepctl_telemetry/notice.py b/packages/deepctl-telemetry/src/deepctl_telemetry/notice.py index b4de4428..ce9f04d3 100644 --- a/packages/deepctl-telemetry/src/deepctl_telemetry/notice.py +++ b/packages/deepctl-telemetry/src/deepctl_telemetry/notice.py @@ -15,9 +15,8 @@ # Golden text, compared byte for byte with tests/golden/notice_*.txt. -# NOTICE_ON shows only with a loopback DEEPCTL_TELEMETRY_DSN (tests and local -# sinks). It names every opt-out: the flag for one run, the env var, the -# config-file key, and the cross-tool DO_NOT_TRACK and CI. +# NOTICE_ON is the default. It names every opt-out: the flag for one run, +# the env var, the config-file key, and the cross-tool DO_NOT_TRACK and CI. NOTICE_ON = ( "Telemetry is on: unexpected errors only, with no flag values, paths or " "keys. Turn off: --no-telemetry, DEEPCTL_TELEMETRY_DISABLED=1, or " @@ -25,8 +24,7 @@ "off too." ) NOTICE_OFF = "Telemetry is off." -# No destination (no loopback DEEPCTL_TELEMETRY_DSN), or the build switch is -# off: what every user of this version sees. +# Only for a build with TELEMETRY_BUILD_ENABLED = False. NOTICE_NONE = "This version of dg sends no telemetry." _installed = False @@ -43,9 +41,10 @@ def render_notice(config: Config) -> str: from .client import _opt_out_source source = _opt_out_source(config) - if source is None: + # "notice": on, and waiting only for the first-run notice (first_run.py). + if source is None or source == "notice": text = NOTICE_ON - elif source in ("build", "dsn"): + elif source == "build": text = NOTICE_NONE else: text = NOTICE_OFF diff --git a/packages/deepctl-telemetry/tests/golden/notice_first_run.txt b/packages/deepctl-telemetry/tests/golden/notice_first_run.txt new file mode 100644 index 00000000..35506a87 --- /dev/null +++ b/packages/deepctl-telemetry/tests/golden/notice_first_run.txt @@ -0,0 +1 @@ +From the next run on, dg reports unexpected errors to Deepgram, with no flag values, paths or keys. Turn off: --no-telemetry, DEEPCTL_TELEMETRY_DISABLED=1, or telemetry.enabled: false in config.yaml. DO_NOT_TRACK=1 and CI turn it off too. This notice is shown once. diff --git a/packages/deepctl-telemetry/tests/golden/readme_telemetry.md b/packages/deepctl-telemetry/tests/golden/readme_telemetry.md index 2e65ee81..d64a2a06 100644 --- a/packages/deepctl-telemetry/tests/golden/readme_telemetry.md +++ b/packages/deepctl-telemetry/tests/golden/readme_telemetry.md @@ -1,5 +1,7 @@ ## Telemetry -This version of dg sends no telemetry: no error reports, usage data or other telemetry, whether a command succeeds or fails. dg still contacts the Deepgram API for the commands you run, and pypi.org to check for updates. +When a command fails with an unexpected error, dg sends one error report to Deepgram's Sentry project. Nothing is sent when a command succeeds, `--help` and `--version` included, or for a usage error or another error dg reports to you. Nothing is sent either until dg has told you about this: the first run at a terminal prints a one-time notice, and reports start with the run after it. -The `DEEPCTL_TELEMETRY_DISABLED` environment variable and the `telemetry.enabled` setting in `config.yaml` are still accepted, and the new `--no-telemetry` flag is accepted too, but none of them has an effect in this version. `DEEPCTL_TELEMETRY_DSN` is now ignored unless it points at the local machine, which is for tests. The last line of `dg --help` says that dg sends no telemetry. +A report holds the exception type, the module, function and line number of each stack frame, the command path, the names of the flags used, and the dg version, operating system, CPU architecture and Python version. It never holds flag values or arguments, file names or paths, environment variables, API keys, request or response data, error messages, log output, variable values, your hostname or your username. [docs/telemetry.md](docs/telemetry.md) lists every field. + +To turn it off, pass `--no-telemetry` for one command, set `DEEPCTL_TELEMETRY_DISABLED=1` or `DO_NOT_TRACK=1`, or put `telemetry.enabled: false` in your `config.yaml`. It is off whenever `CI` is set. To see a report instead of sending it, run a command with `DEEPCTL_TELEMETRY=log`. The last line of `dg --help` says whether telemetry is on. diff --git a/packages/deepctl-telemetry/tests/unit/test_contract.py b/packages/deepctl-telemetry/tests/unit/test_contract.py index 1e85f504..105c20ed 100644 --- a/packages/deepctl-telemetry/tests/unit/test_contract.py +++ b/packages/deepctl-telemetry/tests/unit/test_contract.py @@ -357,7 +357,11 @@ def test_documented_fields_equal_what_a_report_holds( monkeypatch.setattr( telemetry_context, "command_context", - lambda: {"command": "dg listen", "flags": "--model"}, + lambda: { + "command": "dg listen", + "flags": "--model", + "module": "deepctl_cmd_listen.command", + }, ) capturing = _Capturing() real_init = sentry_sdk.init diff --git a/packages/deepctl-telemetry/tests/unit/test_envelopes.py b/packages/deepctl-telemetry/tests/unit/test_envelopes.py index 9437aa29..2ebebd68 100644 --- a/packages/deepctl-telemetry/tests/unit/test_envelopes.py +++ b/packages/deepctl-telemetry/tests/unit/test_envelopes.py @@ -139,8 +139,9 @@ def _config(enabled: bool = True) -> Any: return SimpleNamespace(config_path=path) -def _record_sentinel_command() -> None: - """Record context from a real Click parse of the sentinel argv.""" +def _record_sentinel_command(module: str = "deepctl_cmd_read.command") -> None: + """Record context from a real Click parse of the sentinel argv, as a + command defined in `module` would.""" @click.group() @click.option("--api-key") @@ -151,7 +152,7 @@ def root(api_key: str | None) -> None: @click.option("--text") @click.pass_context def read(ctx: click.Context, text: str | None) -> None: - record_command(ctx) + record_command(ctx, module) result = CliRunner().invoke(root, ARGV[1:], prog_name="dg") assert result.exit_code == 0, result.output @@ -222,6 +223,27 @@ def test_error_envelope_contains_only_allowlisted_fields( assert set(tags) == {"cmd.path", "cmd.flags", "cli.os", "cli.arch", "cli.python"} +@pytest.mark.parametrize( + "module", ["acme_payroll.command", "deepctl_atk.command", "__main__", "", "a b"] +) +def test_plugin_command_name_and_flags_are_not_sent( + transport: CapturingTransport, module: str +) -> None: + """Only a command from one of dg's own packages has its path and flag + names sent; a plugin's are its own identifiers.""" + assert client.init_telemetry(_config(True)) is True + _record_sentinel_command(module) + _fail_with_sentinels() + + ((kind, event),) = _items(transport) + assert kind == "event" + assert set(event["tags"]) == {"cli.os", "cli.arch", "cli.python"} + payload = _serialized(transport) + assert "dg read" not in payload + assert "--text" not in payload + assert "--api-key" not in payload + + def test_user_controlled_module_and_type_names_are_not_sent( transport: CapturingTransport, ) -> None: diff --git a/packages/deepctl-telemetry/tests/unit/test_telemetry.py b/packages/deepctl-telemetry/tests/unit/test_telemetry.py index 0477a1d4..2442ff95 100644 --- a/packages/deepctl-telemetry/tests/unit/test_telemetry.py +++ b/packages/deepctl-telemetry/tests/unit/test_telemetry.py @@ -5,6 +5,7 @@ import os import tempfile import threading +from importlib.metadata import PackageNotFoundError from pathlib import Path from types import SimpleNamespace from typing import Any @@ -43,6 +44,16 @@ def _telemetry_env(monkeypatch: pytest.MonkeyPatch, fresh_state: Any) -> None: monkeypatch.setattr(fresh_state, "_default_config_path", lambda: default) +@pytest.fixture +def released_install(monkeypatch: pytest.MonkeyPatch, fresh_state: Any) -> None: + """As installed from a release, with the first-run notice already + shown. Tests run from a source checkout, which has no built-in + destination. Only for tests that patch the SDK or never report: this is + what lets a report go to Sentry.""" + monkeypatch.setattr(fresh_state, "_released_install", lambda: True) + monkeypatch.setattr(fresh_state, "notice_shown", lambda: True) + + def _default_file(fresh_state: Any) -> Path: path: Path = fresh_state._default_config_path() return path @@ -265,6 +276,8 @@ def test_project_file_cannot_turn_it_off_either( GOLDEN = Path(__file__).resolve().parents[1] / "golden" +# A DEEPCTL_TELEMETRY_DSN that isn't a loopback address (a reserved TLD). +OFF_MACHINE_DSN = "https://k@sentry.invalid/1" REPO_README = Path(__file__).resolve().parents[4] / "README.md" @@ -290,17 +303,32 @@ def test_off_message_matches_golden(self) -> None: golden = (GOLDEN / "notice_off.txt").read_text(encoding="utf-8") assert render_notice(_config(False)) == golden[:-1] - def test_no_destination_message_matches_golden( + def test_default_destination_reads_on( + self, monkeypatch: pytest.MonkeyPatch, released_install: None + ) -> None: + """No DEEPCTL_TELEMETRY_DSN, as for every user: on unless opted out.""" + from deepctl_telemetry.client import DSN_ENV_VAR + from deepctl_telemetry.notice import NOTICE_OFF, NOTICE_ON + + monkeypatch.delenv(DSN_ENV_VAR, raising=False) + assert render_notice(_config(True)) == NOTICE_ON + assert render_notice(_config(None)) == NOTICE_ON + assert render_notice(_config(False)) == NOTICE_OFF + + def test_override_off_this_machine_reads_off( self, monkeypatch: pytest.MonkeyPatch ) -> None: from deepctl_telemetry.client import DSN_ENV_VAR + from deepctl_telemetry.notice import NOTICE_OFF + + monkeypatch.setenv(DSN_ENV_VAR, OFF_MACHINE_DSN) + assert render_notice(_config(True)) == NOTICE_OFF + + def test_build_off_message_matches_golden(self) -> None: from deepctl_telemetry.notice import NOTICE_NONE - monkeypatch.delenv(DSN_ENV_VAR, raising=False) golden = (GOLDEN / "notice_none.txt").read_text(encoding="utf-8") assert golden[:-1] == NOTICE_NONE - assert render_notice(_config(True)) == NOTICE_NONE - assert render_notice(_config(False)) == NOTICE_NONE def test_dim_only_on_a_terminal_without_no_color( self, monkeypatch: pytest.MonkeyPatch @@ -326,10 +354,18 @@ def test_readme_telemetry_section_matches_golden(self) -> None: golden = (GOLDEN / "readme_telemetry.md").read_text(encoding="utf-8") assert readme[start:end] == golden + "\n" - def test_readme_says_nothing_is_sent(self) -> None: + def test_readme_names_every_opt_out(self) -> None: golden = (GOLDEN / "readme_telemetry.md").read_text(encoding="utf-8") - assert "This version of dg sends no telemetry" in golden - assert "sentry.io" not in golden + for switch in ( + "--no-telemetry", + "DEEPCTL_TELEMETRY_DISABLED=1", + "DO_NOT_TRACK=1", + "telemetry.enabled: false", + "`CI`", + "DEEPCTL_TELEMETRY=log", + ): + assert switch in golden, switch + assert "docs/telemetry.md" in golden def _patched_sdk() -> Any: @@ -483,37 +519,452 @@ def test_loopback_override_is_used( "https://k@10.0.0.5/1", "https://k@127.0.0.1.attacker.example/1", "not a url", + "", + " ", ], ) - def test_other_overrides_are_ignored( + def test_other_overrides_turn_it_off( self, monkeypatch: pytest.MonkeyPatch, dsn: str ) -> None: + """Never redirected, and never a fallback to the built-in DSN.""" from deepctl_telemetry import client monkeypatch.setenv(client.DSN_ENV_VAR, dsn) assert client._dsn() is None + assert is_enabled(_config(True)) is False - @pytest.mark.parametrize("dsn", [None, "", " "]) - def test_no_override_means_no_destination( - self, monkeypatch: pytest.MonkeyPatch, dsn: str | None + def test_no_override_means_the_built_in_dsn( + self, monkeypatch: pytest.MonkeyPatch, released_install: None ) -> None: from deepctl_telemetry import client - if dsn is None: - monkeypatch.delenv(client.DSN_ENV_VAR, raising=False) - else: - monkeypatch.setenv(client.DSN_ENV_VAR, dsn) - assert client._dsn() is None + monkeypatch.delenv(client.DSN_ENV_VAR, raising=False) + assert client._dsn() == client.SENTRY_DSN - def test_there_is_no_built_in_dsn(self) -> None: - import inspect + def test_report_goes_to_the_built_in_dsn( + self, fresh_state: Any, monkeypatch: pytest.MonkeyPatch, released_install: None + ) -> None: + monkeypatch.delenv(fresh_state.DSN_ENV_VAR, raising=False) + assert init_telemetry(_config(None)) is True + stack, sdk = _patched_sdk() + with stack: + assert fresh_state.report_exception(RuntimeError("x")) is True + assert sdk.init.call_args.kwargs["dsn"] == fresh_state.SENTRY_DSN + + +EDITABLE = '{"url": "file:///src/cli", "dir_info": {"editable": true}}' +WHEEL = "Wheel-Version: 1.0\n" + + +class TestSourceCheckout: + """dg run from a source checkout has no built-in destination.""" + + @staticmethod + def _installed_as( + monkeypatch: pytest.MonkeyPatch, + tmp_path: Path, + direct_url: Any, + *, + wheel: str | None = WHEEL, + running_installed_copy: bool = True, + ) -> None: + """Make deepctl's install metadata hold `direct_url` as its + direct_url.json (None: no such file; an exception: raised) and + `wheel` as its WHEEL file, with the running `deepctl` package being + the installed copy or another one.""" + import importlib.metadata + import importlib.util + + installed = tmp_path / "site" / "deepctl" / "__init__.py" + running = installed + if not running_installed_copy: + running = tmp_path / "checkout" / "deepctl" / "__init__.py" + for file in {installed, running}: + file.parent.mkdir(parents=True, exist_ok=True) + file.touch() + files = {"WHEEL": wheel, "direct_url.json": direct_url} + + def distribution(name: str) -> Any: + assert name == "deepctl" + if isinstance(direct_url, Exception): + raise direct_url + return SimpleNamespace( + read_text=files.get, + locate_file=lambda name: installed.parents[1] / name, + ) + + def find_spec(name: str) -> Any: + assert name == "deepctl" + return SimpleNamespace(origin=str(running)) + + monkeypatch.setattr(importlib.metadata, "distribution", distribution) + monkeypatch.setattr(importlib.util, "find_spec", find_spec) + + @pytest.mark.parametrize( + ("direct_url", "released"), + [ + (None, True), + ('{"url": "https://files.example/d.whl", "archive_info": {}}', True), + ('{"url": "file:///tmp/build/deepctl", "dir_info": {}}', True), + ('{"url": "file:///tmp/build", "dir_info": {"editable": false}}', True), + (EDITABLE, False), + ("not json", False), + ("[]", False), + (PackageNotFoundError("deepctl"), False), + (OSError("unreadable"), False), + ], + ids=[ + "index", + "wheel-or-archive", + "directory-build", + "editable-false", + "editable", + "bad-json", + "not-a-mapping", + "no-metadata", + "unreadable", + ], + ) + def test_released_install_reads_the_install_metadata( + self, + fresh_state: Any, + monkeypatch: pytest.MonkeyPatch, + tmp_path: Path, + direct_url: Any, + released: bool, + ) -> None: + self._installed_as(monkeypatch, tmp_path, direct_url) + assert fresh_state._released_install() is released + + def test_metadata_no_installer_wrote_is_not_a_release( + self, fresh_state: Any, monkeypatch: pytest.MonkeyPatch, tmp_path: Path + ) -> None: + """An egg-info in the source tree: no WHEEL, and no direct_url.json.""" + self._installed_as(monkeypatch, tmp_path, None, wheel=None) + assert fresh_state._released_install() is False + + def test_another_copy_of_the_code_is_not_a_release( + self, fresh_state: Any, monkeypatch: pytest.MonkeyPatch, tmp_path: Path + ) -> None: + """A release is installed, but a source tree ahead of it is running.""" + self._installed_as(monkeypatch, tmp_path, None, running_installed_copy=False) + assert fresh_state._released_install() is False + + @pytest.mark.parametrize( + ("layout", "released"), + [("release", True), ("egg-info", False), ("tree-ahead-of-release", False)], + ) + def test_against_real_metadata_on_the_path( + self, tmp_path: Path, layout: str, released: bool + ) -> None: + """No stubs: a child Python finds `deepctl` and its metadata on its + own path, as `PYTHONPATH=src` in a checkout makes it do.""" + import subprocess + import sys + + site = tmp_path / "site" + tree = tmp_path / "tree" + for root in (site, tree): + (root / "deepctl").mkdir(parents=True) + (root / "deepctl" / "__init__.py").touch() + info = site / "deepctl-9.9.9.dist-info" + info.mkdir() + (info / "METADATA").write_text("Metadata-Version: 2.1\nName: deepctl\n") + (info / "WHEEL").write_text(WHEEL) + egg = tree / "deepctl.egg-info" + path = [str(site)] + if layout == "egg-info": + # What a build leaves in src/ (gitignored, so it stays around). + egg.mkdir() + (egg / "PKG-INFO").write_text("Metadata-Version: 2.1\nName: deepctl\n") + path = [str(tree)] + elif layout == "tree-ahead-of-release": + path = [str(tree), str(site)] + code = ( + "import sys\n" + f"sys.path[:0] = {path!r}\n" + "from deepctl_telemetry import client\n" + "assert 'deepctl' not in sys.modules\n" + "print(client._released_install())\n" + ) + env = {k: v for k, v in os.environ.items() if k != "PYTHONPATH"} + proc = subprocess.run( + [sys.executable, "-c", code], capture_output=True, text=True, env=env + ) + assert proc.returncode == 0, proc.stderr + assert proc.stdout.strip() == str(released) + + def test_no_destination_without_an_override( + self, fresh_state: Any, monkeypatch: pytest.MonkeyPatch, tmp_path: Path + ) -> None: + import sys + + self._installed_as(monkeypatch, tmp_path, EDITABLE) + monkeypatch.delenv(fresh_state.DSN_ENV_VAR, raising=False) + hook = sys.excepthook + assert fresh_state._dsn() is None + assert init_telemetry(_config(True)) is False + assert fresh_state._state["opt_out"] == "source" + assert sys.excepthook is hook + assert render_notice(_config(True)) == "Telemetry is off." + fresh_state._state["enabled"] = True # even if state were forced on + with patch("sentry_sdk.init") as mock_init: + assert fresh_state.report_exception(RuntimeError("x")) is False + mock_init.assert_not_called() + + def test_a_loopback_sink_still_works( + self, fresh_state: Any, monkeypatch: pytest.MonkeyPatch, tmp_path: Path + ) -> None: + self._installed_as(monkeypatch, tmp_path, EDITABLE) + monkeypatch.setenv(fresh_state.DSN_ENV_VAR, "http://k@127.0.0.1:9/1") + assert fresh_state._dsn() == "http://k@127.0.0.1:9/1" + assert init_telemetry(_config(True)) is True + + +class TestFirstRunNotice: + """Nothing goes to the built-in destination until a run after the one + that showed the notice.""" + + @pytest.fixture + def cache( + self, fresh_state: Any, monkeypatch: pytest.MonkeyPatch, tmp_path: Path + ) -> Path: + """A released install with no override and an empty cache, run by a + person at a terminal.""" + from deepctl import _cache + from deepctl_telemetry import first_run + + root = tmp_path / "cache" + monkeypatch.setattr(_cache, "real_cache_root", lambda: str(root)) + monkeypatch.setattr(fresh_state, "_released_install", lambda: True) + monkeypatch.delenv(fresh_state.DSN_ENV_VAR, raising=False) + monkeypatch.setattr(first_run, "_person_at_terminal", lambda: True) + return root + + def test_notice_matches_golden(self) -> None: + from deepctl_telemetry.first_run import FIRST_RUN_NOTICE + + golden = (GOLDEN / "notice_first_run.txt").read_text(encoding="utf-8") + assert golden.endswith("\n") + assert FIRST_RUN_NOTICE == golden[:-1] + for switch in ( + "--no-telemetry", + "DEEPCTL_TELEMETRY_DISABLED=1", + "telemetry.enabled: false", + "DO_NOT_TRACK=1", + "CI", + ): + assert switch in FIRST_RUN_NOTICE, switch + + def test_the_run_that_shows_it_sends_nothing( + self, fresh_state: Any, cache: Path + ) -> None: + import sys + + from deepctl_telemetry import claim_first_run_notice + from deepctl_telemetry.first_run import FIRST_RUN_NOTICE + + hook = sys.excepthook + assert init_telemetry(_config(None)) is False + assert fresh_state._state["opt_out"] == "notice" + assert sys.excepthook is hook + assert claim_first_run_notice() == FIRST_RUN_NOTICE + with patch("sentry_sdk.init") as mock_init: + assert fresh_state.report_exception(RuntimeError("x")) is False + mock_init.assert_not_called() + + def test_the_next_run_reports_and_stays_quiet( + self, fresh_state: Any, cache: Path, monkeypatch: pytest.MonkeyPatch + ) -> None: + from deepctl_telemetry import claim_first_run_notice + + init_telemetry(_config(None)) + assert claim_first_run_notice() is not None + assert claim_first_run_notice() is None # once only + + monkeypatch.setattr(fresh_state, "_state", fresh_state._fresh_state()) + assert init_telemetry(_config(None)) is True + assert claim_first_run_notice() is None + stack, sdk = _patched_sdk() + with stack: + assert fresh_state.report_exception(RuntimeError("x")) is True + assert sdk.init.call_args.kwargs["dsn"] == fresh_state.SENTRY_DSN + + def test_marker_is_private(self, fresh_state: Any, cache: Path) -> None: + import stat + import sys + + from deepctl_telemetry import claim_first_run_notice + + init_telemetry(_config(None)) + claim_first_run_notice() + marker = cache / "telemetry" / "notice-shown" + assert marker.read_bytes() == b"" + if sys.platform != "win32": + assert stat.S_IMODE(marker.stat().st_mode) == 0o600 + assert stat.S_IMODE(marker.parent.stat().st_mode) == 0o700 + + def test_not_shown_unless_a_person_is_at_the_terminal( + self, fresh_state: Any, cache: Path, monkeypatch: pytest.MonkeyPatch + ) -> None: + """A script, a container or an AI agent session: no notice, so the + install keeps waiting and sends nothing.""" + from deepctl_telemetry import claim_first_run_notice, first_run + + monkeypatch.setattr(first_run, "_person_at_terminal", lambda: False) + init_telemetry(_config(None)) + assert claim_first_run_notice() is None + assert not (cache / "telemetry" / "notice-shown").exists() + assert init_telemetry(_config(None)) is False + + @pytest.mark.parametrize( + ("tty", "agent", "expected"), + [(True, False, True), (False, False, False), (True, True, False)], + ) + def test_person_at_terminal( + self, monkeypatch: pytest.MonkeyPatch, tty: bool, agent: bool, expected: bool + ) -> None: + import sys + + from deepctl_core import output + from deepctl_telemetry import first_run + + monkeypatch.setattr(sys, "stderr", SimpleNamespace(isatty=lambda: tty)) + monkeypatch.setattr(output, "is_agentic", lambda: agent) + monkeypatch.setattr(output, "is_ai_agent", lambda: agent) + assert first_run._person_at_terminal() is expected + + def test_not_shown_when_it_cannot_be_recorded( + self, fresh_state: Any, cache: Path + ) -> None: + """Printed at most once: with nowhere to record it, never.""" + import sys + + from deepctl_telemetry import claim_first_run_notice + + if sys.platform == "win32": + pytest.skip("POSIX ownership rules") + cache.mkdir(mode=0o777) + cache.chmod(0o777) # others can write: not a directory dg trusts + init_telemetry(_config(None)) + assert claim_first_run_notice() is None + assert init_telemetry(_config(None)) is False + + def test_a_marker_others_can_write_does_not_count( + self, fresh_state: Any, cache: Path + ) -> None: + import sys + + if sys.platform == "win32": + pytest.skip("POSIX ownership rules") + marker = cache / "telemetry" / "notice-shown" + marker.parent.mkdir(parents=True, mode=0o700) + cache.chmod(0o700) + marker.touch() + marker.chmod(0o666) + assert init_telemetry(_config(None)) is False + assert fresh_state._state["opt_out"] == "notice" + + def test_not_shown_to_someone_who_opted_out( + self, fresh_state: Any, cache: Path + ) -> None: + from deepctl_telemetry import claim_first_run_notice + + assert init_telemetry(_config(False)) is False + assert fresh_state._state["opt_out"] == "config" + assert claim_first_run_notice() is None + assert not cache.exists() + + def test_help_footer_reads_on_while_it_waits( + self, fresh_state: Any, cache: Path + ) -> None: + from deepctl_telemetry.notice import NOTICE_ON + + assert render_notice(_config(None)) == NOTICE_ON + + def test_a_local_sink_does_not_wait( + self, fresh_state: Any, cache: Path, monkeypatch: pytest.MonkeyPatch + ) -> None: + """Nothing leaves this machine, so there is nothing to announce.""" + from deepctl_telemetry import claim_first_run_notice + + monkeypatch.setenv(fresh_state.DSN_ENV_VAR, "http://k@127.0.0.1:9/1") + assert init_telemetry(_config(None)) is True + assert claim_first_run_notice() is None + assert not cache.exists() + + def test_log_mode_does_not_wait( + self, fresh_state: Any, cache: Path, monkeypatch: pytest.MonkeyPatch + ) -> None: + monkeypatch.setenv(fresh_state.MODE_ENV_VAR, "log") + assert init_telemetry(_config(None)) is True + assert not cache.exists() + + +# The Sentry project that dg 0.2.21 to 0.4.0 reported to. It is retired: +# no build may send to it again. +RETIRED_KEY = "d7a2aabbf772218e3bbe89266999af70" +RETIRED_PROJECT_ID = "4510993603362816" + + +def _shipped_sources() -> dict[str, str]: + """Every Python file that ships in a wheel, by repo-relative path.""" + root = Path(__file__).resolve().parents[4] + if not (root / "packages").is_dir(): + pytest.skip("workspace not available") + files = [*(root / "src").rglob("*.py"), *(root / "packages").glob("*/src/**/*.py")] + assert len(files) > 50 + return { + file.relative_to(root).as_posix(): file.read_text( + encoding="utf-8", errors="replace" + ) + for file in files + } + + +class TestBuiltInDsn: + def test_it_is_the_deepgram_cli_project(self) -> None: + import re + from urllib.parse import urlsplit from deepctl_telemetry import client - source = inspect.getsource(client) - assert not hasattr(client, "SENTRY_DSN") - assert "sentry.io" not in source - assert not [ln for ln in source.splitlines() if ln.startswith("SENTRY_DSN")] + parts = urlsplit(client.SENTRY_DSN) + assert parts.scheme == "https" + assert parts.hostname == "o206115.ingest.us.sentry.io" + assert parts.port is None + assert parts.path == "/4512538396459008" + assert re.fullmatch(r"[0-9a-f]{32}", parts.username or "") + # A public key only: a DSN with a secret part must never ship. + assert parts.password is None + assert not parts.query + assert not parts.fragment + + def test_it_is_not_the_retired_project(self) -> None: + from deepctl_telemetry import client + + assert RETIRED_KEY not in client.SENTRY_DSN + assert RETIRED_PROJECT_ID not in client.SENTRY_DSN + + def test_no_shipped_source_names_the_retired_project(self) -> None: + for name, text in _shipped_sources().items(): + assert RETIRED_KEY not in text, name + assert RETIRED_PROJECT_ID not in text, name + + def test_it_is_the_only_sentry_address_in_shipped_source(self) -> None: + import re + + found = { + (name, match) + for name, text in _shipped_sources().items() + for match in re.findall(r"[\w.-]*sentry\.io", text) + } + assert found == { + ( + "packages/deepctl-telemetry/src/deepctl_telemetry/client.py", + "o206115.ingest.us.sentry.io", + ) + } class TestBuildSwitch: @@ -542,12 +993,12 @@ def test_report_never_touches_the_sdk(self, fresh_state) -> None: mock_init.assert_not_called() -class TestNoDestination: - """Without a loopback DEEPCTL_TELEMETRY_DSN, nothing is set up or sent.""" +class TestOverrideOffThisMachine: + """A DEEPCTL_TELEMETRY_DSN that isn't loopback: nothing is set up or sent.""" @pytest.fixture(autouse=True) - def _no_dsn(self, fresh_state, monkeypatch: pytest.MonkeyPatch) -> None: - monkeypatch.delenv(fresh_state.DSN_ENV_VAR, raising=False) + def _off_machine_dsn(self, fresh_state, monkeypatch: pytest.MonkeyPatch) -> None: + monkeypatch.setenv(fresh_state.DSN_ENV_VAR, OFF_MACHINE_DSN) @pytest.fixture def sdk(self, monkeypatch: pytest.MonkeyPatch) -> Any: @@ -627,11 +1078,8 @@ def test_sdk_is_not_imported(self, fresh_state) -> None: "assert 'sentry_sdk' not in sys.modules, 'sentry_sdk imported'\n" "print('OK')\n" ) - env = { - k: v - for k, v in os.environ.items() - if k not in (fresh_state.DSN_ENV_VAR, DISABLE_ENV_VAR) - } + env = {k: v for k, v in os.environ.items() if k != DISABLE_ENV_VAR} + assert env[fresh_state.DSN_ENV_VAR] == OFF_MACHINE_DSN result = subprocess.run( [sys.executable, "-c", code], capture_output=True, diff --git a/src/deepctl/_cache.py b/src/deepctl/_cache.py index 3279460c..3a0a501b 100644 --- a/src/deepctl/_cache.py +++ b/src/deepctl/_cache.py @@ -57,8 +57,8 @@ "DEEPCTL_TELEMETRY_DISABLED", "DO_NOT_TRACK", "DEEPCTL_TELEMETRY", - # A loopback sink turns the closing "sends no telemetry" line into - # "Telemetry is on". + # Set to anything but a loopback sink, it turns the closing "Telemetry + # is on" line into "Telemetry is off." "DEEPCTL_TELEMETRY_DSN", "CI", "DEEPCTL_EAGER_LOAD", diff --git a/src/deepctl/_cli.py b/src/deepctl/_cli.py index 21f82fe5..2a8b4143 100644 --- a/src/deepctl/_cli.py +++ b/src/deepctl/_cli.py @@ -644,12 +644,24 @@ def _no_telemetry_cb(ctx: click.Context, param: click.Parameter, value: bool) -> pass -def _init_telemetry(config: Config) -> None: - """Decide telemetry from the resolved Config. Never loads the SDK.""" +def _init_telemetry(config: Config, quiet: bool) -> None: + """Decide telemetry from the resolved Config. Never loads the SDK. + + Reports start only after dg has said, once, that they are on: the first + run at a terminal prints that notice on stderr (not under ``--quiet``, + and not for help, which prints only the help) and sends nothing. + """ try: - from deepctl_telemetry import init_telemetry + from deepctl_telemetry import claim_first_run_notice, init_telemetry init_telemetry(config) + if quiet or _is_help_run(sys.argv[1:] if _run_args is None else _run_args): + return + notice = claim_first_run_notice() + if notice is not None: + from deepctl_core import output + + output.print_info(notice, stderr=True) except Exception: pass @@ -795,7 +807,7 @@ def _show_version(ctx: click.Context, param: click.Parameter, value: bool) -> No is_eager=True, expose_value=False, callback=_no_telemetry_cb, - help="No effect: this version of dg sends no telemetry", + help="Send no error report for this run", ) @click.option( "--non-interactive", @@ -904,7 +916,7 @@ def cli( # Telemetry is decided here, after option parsing, so --config and # --no-telemetry are honored. if ctx.obj["config"] is not None: - _init_telemetry(ctx.obj["config"]) + _init_telemetry(ctx.obj["config"], quiet) _commands_loaded = False diff --git a/tests/unit/test_cache.py b/tests/unit/test_cache.py index 1a4c4c36..80993ca3 100644 --- a/tests/unit/test_cache.py +++ b/tests/unit/test_cache.py @@ -694,8 +694,8 @@ def test_pi_path_changes_the_key( def test_telemetry_sink_changes_the_key( self, homes: Homes, monkeypatch: pytest.MonkeyPatch ) -> None: - """With a loopback telemetry sink, root --help ends "Telemetry is - on" instead of "This version of dg sends no telemetry".""" + """DEEPCTL_TELEMETRY_DSN can change the last line of root --help + (set to anything but a loopback sink, it reads "Telemetry is off.").""" monkeypatch.delenv("DEEPCTL_TELEMETRY_DSN", raising=False) assert _cache.key_inputs()["env"]["DEEPCTL_TELEMETRY_DSN"] is None monkeypatch.setenv("DEEPCTL_TELEMETRY_DSN", "http://k@127.0.0.1:9/1") diff --git a/tests/unit/test_telemetry_wiring.py b/tests/unit/test_telemetry_wiring.py index 48581dfe..efc6b90b 100644 --- a/tests/unit/test_telemetry_wiring.py +++ b/tests/unit/test_telemetry_wiring.py @@ -22,6 +22,8 @@ from deepctl_core import BaseCommand DEAD_DSN = "http://public@127.0.0.1:9/1" +# A DEEPCTL_TELEMETRY_DSN that isn't a loopback address (a reserved TLD). +OFF_MACHINE_DSN = "https://k@sentry.invalid/1" @pytest.fixture @@ -425,7 +427,9 @@ def probe_boom(): ) -def _probe_env(tmp_path: Path, dsn: str | None = DEAD_DSN) -> dict[str, str]: +def _probe_env(tmp_path: Path, dsn: str = DEAD_DSN) -> dict[str, str]: + """A child's environment with telemetry on. It always sets + DEEPCTL_TELEMETRY_DSN: without it a child would report to Sentry.""" env = { key: value for key, value in os.environ.items() @@ -433,8 +437,8 @@ def _probe_env(tmp_path: Path, dsn: str | None = DEAD_DSN) -> dict[str, str]: not in ("DEEPCTL_TELEMETRY_DISABLED", "DEEPCTL_TELEMETRY_DSN", "CI", "DO_NOT_TRACK") and not key.startswith("DEEPGRAM_") } - if dsn is not None: - env["DEEPCTL_TELEMETRY_DSN"] = dsn + assert dsn + env["DEEPCTL_TELEMETRY_DSN"] = dsn env.update( { "HOME": str(tmp_path), @@ -459,7 +463,7 @@ def _probe( args: list[str], tmp_path: Path, stdin: str | None = None, - dsn: str | None = DEAD_DSN, + dsn: str = DEAD_DSN, ) -> tuple[dict, str]: result = subprocess.run( [sys.executable, "-X", "importtime", "-c", _PROBE, json.dumps(args)], @@ -504,11 +508,156 @@ def test_opt_out_error_does_not_load_sdk(self, tmp_path: Path) -> None: assert probe["sdk_loaded"] is False -class TestNoDestination: - """No DEEPCTL_TELEMETRY_DSN, as for every user: nothing is reported.""" +class TestBuiltInDestination: + """No DEEPCTL_TELEMETRY_DSN and a released install that has shown the + first-run notice, as for every user. In this process only, with the SDK + patched, so nothing can reach Sentry.""" + + @pytest.fixture(autouse=True) + def _no_override(self, telemetry_on, monkeypatch: pytest.MonkeyPatch) -> None: + monkeypatch.delenv(telemetry_on.DSN_ENV_VAR, raising=False) + monkeypatch.setattr(telemetry_on, "_released_install", lambda: True) + monkeypatch.setattr(telemetry_on, "notice_shown", lambda: True) + + def test_unexpected_error_is_reported_to_it( + self, telemetry_on, boom_command + ) -> None: + with patch("sentry_sdk.init") as mock_init, patch( + "sentry_sdk.capture_exception" + ) as mock_capture, patch("sentry_sdk.flush"): + assert _run_main(["dg", boom_command]) == 1 + mock_init.assert_called_once() + assert mock_init.call_args.kwargs["dsn"] == telemetry_on.SENTRY_DSN + mock_capture.assert_called_once() + + def test_help_says_it_is_on( + self, telemetry_on, capsys: pytest.CaptureFixture[str] + ) -> None: + with patch("sentry_sdk.init") as mock_init: + assert _run_main(["dg", "--help"]) == 0 + mock_init.assert_not_called() + last = capsys.readouterr().out.rstrip().splitlines()[-1] + assert last.startswith("Telemetry is on") + + def test_no_telemetry_flag_is_honored(self, telemetry_on, boom_command) -> None: + with patch("sentry_sdk.init") as mock_init: + assert _run_main(["dg", "--no-telemetry", boom_command]) == 1 + mock_init.assert_not_called() + assert telemetry_on._state["opt_out"] == "flag" + + +class TestSourceCheckout: + """No DEEPCTL_TELEMETRY_DSN and an editable install, as for a + contributor: nothing is reported.""" + + @pytest.fixture(autouse=True) + def _editable(self, telemetry_on, monkeypatch: pytest.MonkeyPatch) -> None: + monkeypatch.delenv(telemetry_on.DSN_ENV_VAR, raising=False) + monkeypatch.setattr(telemetry_on, "_released_install", lambda: False) + + def test_unexpected_error_sends_nothing(self, telemetry_on, boom_command) -> None: + with patch("sentry_sdk.init") as mock_init: + assert _run_main(["dg", boom_command]) == 1 + mock_init.assert_not_called() + assert telemetry_on._state["opt_out"] == "source" + + def test_help_says_it_is_off( + self, telemetry_on, capsys: pytest.CaptureFixture[str] + ) -> None: + _run_main(["dg", "--help"]) + assert capsys.readouterr().out.rstrip().endswith("Telemetry is off.") + + +class TestFirstRunNotice: + """A released install with no override that hasn't shown the notice yet, + run by a person at a terminal. In this process only, with the SDK + patched, so nothing can reach Sentry.""" + + @pytest.fixture + def marker( + self, telemetry_on, monkeypatch: pytest.MonkeyPatch, tmp_path: Path + ) -> Path: + from deepctl import _cache + from deepctl_telemetry import first_run + + monkeypatch.delenv(telemetry_on.DSN_ENV_VAR, raising=False) + monkeypatch.setattr(telemetry_on, "_released_install", lambda: True) + monkeypatch.setattr(_cache, "real_cache_root", lambda: str(tmp_path / "cache")) + monkeypatch.setattr(first_run, "_person_at_terminal", lambda: True) + return tmp_path / "cache" / "telemetry" / "notice-shown" + + @pytest.fixture + def printed(self, monkeypatch: pytest.MonkeyPatch) -> list[str]: + """What dg printed with print_info on stderr.""" + from deepctl_core import output + + lines: list[str] = [] + + def print_info(message: str, *, stderr: bool = False) -> None: + if stderr: + lines.append(message) + + monkeypatch.setattr(output, "print_info", print_info) + return lines + + def test_first_run_prints_it_and_sends_nothing( + self, telemetry_on, marker: Path, printed: list[str], boom_command + ) -> None: + from deepctl_telemetry.first_run import FIRST_RUN_NOTICE + + with patch("sentry_sdk.init") as mock_init: + assert _run_main(["dg", boom_command]) == 1 + mock_init.assert_not_called() + assert telemetry_on._state["opt_out"] == "notice" + assert printed == [FIRST_RUN_NOTICE] + assert marker.exists() + + def test_second_run_reports_and_prints_nothing( + self, telemetry_on, marker: Path, printed: list[str], boom_command + ) -> None: + with patch("sentry_sdk.init") as mock_init, patch( + "sentry_sdk.capture_exception" + ) as mock_capture, patch("sentry_sdk.flush"): + assert _run_main(["dg", boom_command]) == 1 + mock_init.assert_not_called() + del printed[:] + assert _run_main(["dg", boom_command]) == 1 + mock_init.assert_called_once() + assert mock_init.call_args.kwargs["dsn"] == telemetry_on.SENTRY_DSN + mock_capture.assert_called_once() + assert printed == [] + + @pytest.mark.parametrize( + "argv", + [["--quiet", "{boom}"], ["--help"], ["{boom}", "--help"], ["help"]], + ids=["quiet", "root-help", "command-help", "help-command"], + ) + def test_runs_that_do_not_show_it_leave_it_for_later( + self, telemetry_on, marker: Path, printed: list[str], boom_command, argv + ) -> None: + args = [arg.format(boom=boom_command) for arg in argv] + with patch("sentry_sdk.init") as mock_init: + _run_main(["dg", *args]) + mock_init.assert_not_called() + assert printed == [] + assert not marker.exists() + + def test_not_shown_to_someone_who_opted_out( + self, telemetry_on, marker: Path, printed: list[str], boom_command, tmp_path + ) -> None: + config = _opt_out_config(tmp_path) + with patch("sentry_sdk.init") as mock_init: + assert _run_main(["dg", "--config", config, boom_command]) == 1 + mock_init.assert_not_called() + assert printed == [] + assert not marker.exists() + + +class TestOverrideOffThisMachine: + """A DEEPCTL_TELEMETRY_DSN that isn't loopback: nothing is reported.""" def test_unexpected_error_sends_nothing(self, tmp_path: Path) -> None: - probe, stderr = _probe(["probe-boom"], tmp_path, dsn=None) + probe, stderr = _probe(["probe-boom"], tmp_path, dsn=OFF_MACHINE_DSN) assert probe["code"] == 1 assert probe["enabled"] is False assert probe["opt_out"] == "dsn" @@ -517,16 +666,14 @@ def test_unexpected_error_sends_nothing(self, tmp_path: Path) -> None: assert importtime, "no -X importtime output" assert not [ln for ln in importtime if "sentry_sdk" in ln] - def test_help_says_nothing_is_sent(self, tmp_path: Path) -> None: + def test_help_says_it_is_off(self, tmp_path: Path) -> None: result = subprocess.run( [sys.executable, "-c", "from deepctl.main import main; main()", "--help"], capture_output=True, text=True, - env=_probe_env(tmp_path, dsn=None), + env=_probe_env(tmp_path, dsn=OFF_MACHINE_DSN), timeout=120, check=False, ) assert result.returncode == 0, result.stderr - assert result.stdout.rstrip().endswith( - "This version of dg sends no telemetry." - ) + assert result.stdout.rstrip().endswith("Telemetry is off.")