:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
fix(hogli): trustworthy telemetry signals (#60312)
Raúl Negrón-Otero20f6b6762f9c
diff --git a/tools/hogli-commands/hogli_commands/telemetry_commands.py b/tools/hogli-commands/hogli_commands/telemetry_commands.pyindex 9f546f083173..49a9e04f1ba0 100644--- a/tools/hogli-commands/hogli_commands/telemetry_commands.py+++ b/tools/hogli-commands/hogli_commands/telemetry_commands.py@@ -2,6 +2,8 @@from __future__ import annotations+import os+import clickfrom hogli import telemetry@@ -20,15 +22,13 @@ def telemetry_off() -> None:@click.command(name="telemetry:status", help="Show current telemetry settings")def telemetry_status() -> None:- import os-enabled = telemetry.is_enabled()config_path = telemetry.get_config_path()click.echo(f"Telemetry: {'enabled' if enabled else 'disabled'}")# Show which mechanism controls the state- if os.environ.get("CI"):+ if telemetry.is_ci():click.echo("Controlled by: CI environment detected")elif os.environ.get("POSTHOG_TELEMETRY_OPT_OUT") == "1":click.echo("Controlled by: POSTHOG_TELEMETRY_OPT_OUT=1")diff --git a/tools/hogli/src/hogli/cli.py b/tools/hogli/src/hogli/cli.pyindex 7886418b8e1f..2a4ce1e219f1 100644--- a/tools/hogli/src/hogli/cli.py+++ b/tools/hogli/src/hogli/cli.py@@ -188,12 +188,16 @@ def cli(ctx: click.Context) -> None:in_git_hook = os.environ.get("GIT_DIR") is not None or os.environ.get("HUSKY") is not Noneif ctx.invoked_subcommand not in {"meta:check", "help"} and not in_git_hook:_auto_update_manifest()+ # telemetry:on still shows the notice (it arms tracking by setting+ # first_run_notice_shown); only off/status suppress it. This set is+ # intentionally narrower than _TELEMETRY_META_COMMANDS below.if ctx.invoked_subcommand not in {"telemetry:off", "telemetry:status"}:telemetry.show_first_run_notice_if_needed()# Fire early so long-running commands (e.g. hogli start) are always counted- # even if the process is killed without a clean exit.- if ctx.invoked_subcommand and ctx.invoked_subcommand != "telemetry:off":+ # even if the process is killed without a clean exit. Gated identically to+ # command_completed so the two events form matched pairs.+ if _should_track(ctx.invoked_subcommand):telemetry.track("command_started", {"command": ctx.invoked_subcommand, **_env_properties(ctx.invoked_subcommand)})@@ -512,13 +516,12 @@ _load_boot_modules()def _env_properties(command: str | None = None) -> dict[str, Any]:"""Static environment properties shared across telemetry events."""- ci_env_vars = ("CI", "GITHUB_ACTIONS", "JENKINS_URL", "GITLAB_CI", "CIRCLECI", "BUILDKITE")props: dict[str, Any] = {"terminal_width": shutil.get_terminal_size().columns,"os": platform.system(),"arch": platform.machine(),"python_version": platform.python_version(),- "is_ci": any(os.environ.get(v) for v in ci_env_vars),+ "is_ci": telemetry.is_ci(),}for hook in telemetry_property_hooks:try:@@ -528,20 +531,47 @@ def _env_properties(command: str | None = None) -> dict[str, Any]:return props+# Telemetry commands manage telemetry itself; tracking them would pollute the+# dataset with self-referential noise, so they emit no command events.+_TELEMETRY_META_COMMANDS = frozenset({"telemetry:on", "telemetry:off", "telemetry:status"})+++def _should_track(command: str | None) -> bool:+ """Whether a subcommand should emit command_started / command_completed.++ Requires a real subcommand (so bare ``hogli`` / ``--help`` don't fire a+ completed event with no matching started event) and excludes the telemetry+ management commands.+ """+ return bool(command) and command not in _TELEMETRY_META_COMMANDS+++def _outcome(exit_code: int) -> str:+ """Classify an exit code so signal kills are distinct from real failures."""+ if exit_code == 0:+ return "success"+ # Killed by a signal: a negative subprocess returncode, or the shell's+ # 128 + signum convention (e.g. 130 SIGINT). Exactly 128 is excluded -- it's+ # an application-error idiom (e.g. git's fatal errors), not a signal.+ if exit_code < 0 or exit_code > 128:+ return "interrupted"+ return "error"++def _fire_telemetry(ctx: click.Context, exit_code: int) -> None:"""Send a command_completed telemetry event. Never raises."""command = ctx.invoked_subcommand- # Skip when CLI itself errors before reaching a subcommand (e.g. bad flag)- if command is None and exit_code != 0:+ if not _should_track(command):returntry:start_time: float = ctx.meta.get("hogli.start_time", 0.0)duration_s = _time.monotonic() - start_timeprops: dict[str, Any] = {"command": command,- "command_category": get_category_for_command(command) if command else None,+ "command_category": get_category_for_command(command),"duration_s": round(duration_s, 3),"exit_code": exit_code,+ "outcome": _outcome(exit_code),"has_extra_argv": ctx.meta.get("hogli.has_extra_argv", False),**_env_properties(command),}diff --git a/tools/hogli/src/hogli/telemetry.py b/tools/hogli/src/hogli/telemetry.pyindex 8241b2c533bf..54a81174b004 100644--- a/tools/hogli/src/hogli/telemetry.py+++ b/tools/hogli/src/hogli/telemetry.py@@ -9,7 +9,7 @@ Telemetry is **disabled** unless an API key is configured via theframework never emit events to PostHog's project by default.Opt-out precedence:- CI=* -> POSTHOG_TELEMETRY_OPT_OUT=1 -> DO_NOT_TRACK=1 -> config enabled: false -> no api_key+ CI (any common provider) -> POSTHOG_TELEMETRY_OPT_OUT=1 -> DO_NOT_TRACK=1 -> config enabled: false -> no api_keyConfig file: ~/.config/posthog/hogli_telemetry.json"""@@ -33,6 +33,20 @@ from hogli.manifest import get_manifest_DEFAULT_HOST = "https://us.i.posthog.com"+# Environment variables set by common CI providers. Presence of any one means+# we're in CI: telemetry is disabled, and (where enabled) the `is_ci` event+# property is set from this same list so the gate and the label never diverge.+# Depot CI runners are drop-in GitHub Actions runners and set CI/GITHUB_ACTIONS,+# so they're already covered. Depot sandboxes expose no stable CI marker, and+# DEPOT_TOKEN also lives on developer laptops, so gating on it would wrongly+# suppress real local signal -- deliberately not listed here.+_CI_ENV_VARS = ("CI", "GITHUB_ACTIONS", "JENKINS_URL", "GITLAB_CI", "CIRCLECI", "BUILDKITE")+++def is_ci() -> bool:+ """True when any common CI provider's environment variable is present."""+ return any(os.environ.get(v) for v in _CI_ENV_VARS)+# ---------------------------------------------------------------------------# Config helpers@@ -100,7 +114,7 @@ class TelemetryClient:return self._telemetry_config.get("api_key", "")def is_enabled(self) -> bool:- if os.environ.get("CI"):+ if is_ci():return Falseif os.environ.get("POSTHOG_TELEMETRY_OPT_OUT") == "1":return Falsediff --git a/tools/hogli/tests/test_telemetry.py b/tools/hogli/tests/test_telemetry.pyindex cf6bb00642da..9c2c1f438338 100644--- a/tools/hogli/tests/test_telemetry.py+++ b/tools/hogli/tests/test_telemetry.py@@ -10,10 +10,12 @@ from unittest.mock import patchfrom click.testing import CliRunnerfrom hogli import telemetry-from hogli.cli import cli+from hogli.cli import _outcome, _should_track, cli_TELEMETRY_ENV_VARS = (- "CI",+ # Every CI marker the gate checks must be cleared, otherwise the suite+ # running on GitHub Actions (GITHUB_ACTIONS=1) would see telemetry disabled.+ *telemetry._CI_ENV_VARS,"POSTHOG_TELEMETRY_OPT_OUT","DO_NOT_TRACK","POSTHOG_TELEMETRY_HOST",@@ -40,6 +42,9 @@ def test_is_enabled_by_default():({"POSTHOG_TELEMETRY_OPT_OUT": "1"}, {}),({"DO_NOT_TRACK": "1"}, {}),({"CI": "true"}, {}),+ ({"GITHUB_ACTIONS": "true"}, {}),+ ({"BUILDKITE": "true"}, {}),+ ({"GITLAB_CI": "true"}, {}),({"POSTHOG_TELEMETRY_OPT_OUT": "1"}, {"enabled": True}),],)@@ -51,6 +56,13 @@ def test_is_disabled(monkeypatch: pytest.MonkeyPatch, telemetry_config: Path, enassert telemetry.is_enabled() is False[email protected]("ci_var", telemetry._CI_ENV_VARS)+def test_is_ci_detects_each_provider(monkeypatch: pytest.MonkeyPatch, ci_var: str):+ assert telemetry.is_ci() is False+ monkeypatch.setenv(ci_var, "true")+ assert telemetry.is_ci() is True++def test_is_disabled_when_no_api_key_configured(monkeypatch: pytest.MonkeyPatch) -> None:"""Standalone hogli users without a telemetry key get no-op telemetry by default."""@@ -192,5 +204,53 @@ class TestInvokeTelemetry:completed = next(e for e in batch if e["event"] == "command_completed")assert completed["properties"]["command"] == "quickstart"assert completed["properties"]["exit_code"] == 0+ assert completed["properties"]["outcome"] == "success"assert "duration_s" in completed["properties"]assert "is_ci" in completed["properties"]++ @pytest.mark.parametrize("command", ["telemetry:on", "telemetry:off", "telemetry:status"])+ def test_management_commands_emit_no_events(+ self, monkeypatch: pytest.MonkeyPatch, telemetry_config: Path, command: str+ ):+ telemetry_config.write_text(+ json.dumps({"enabled": True, "anonymous_id": "test-id", "first_run_notice_shown": True})+ )+ monkeypatch.setenv("POSTHOG_TELEMETRY_HOST", "http://localhost")+ monkeypatch.setenv("POSTHOG_TELEMETRY_API_KEY", "test-key")+ with patch.object(telemetry._client, "_send_batch") as mock_send:+ result = CliRunner().invoke(cli, [command])+ assert result.exit_code == 0+ mock_send.assert_not_called()+++class TestShouldTrack:+ @pytest.mark.parametrize(+ "command, expected",+ [+ ("test", True),+ ("migrations:run", True),+ (None, False),+ ("telemetry:on", False),+ ("telemetry:off", False),+ ("telemetry:status", False),+ ],+ )+ def test_should_track(self, command, expected):+ assert _should_track(command) is expected+++class TestOutcome:+ @pytest.mark.parametrize(+ "exit_code, expected",+ [+ (0, "success"),+ (1, "error"),+ (2, "error"),+ (128, "error"), # application-error idiom (e.g. git fatal), not a signal+ (130, "interrupted"), # SIGINT (Ctrl-C)+ (143, "interrupted"), # SIGTERM+ (-13, "interrupted"), # subprocess killed by signal+ ],+ )+ def test_outcome(self, exit_code, expected):+ assert _outcome(exit_code) == expected