: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
feat(devbox): record tailnet failure cause (#83713)
Raúl Negrón-Oterocc09e385044c
diff --git a/tools/hogli-commands/hogli_commands/devbox/cli.py b/tools/hogli-commands/hogli_commands/devbox/cli.pyindex b9eb124795ff..6b275d98fdfa 100644--- a/tools/hogli-commands/hogli_commands/devbox/cli.py+++ b/tools/hogli-commands/hogli_commands/devbox/cli.py@@ -19,6 +19,7 @@ from pathlib import Pathfrom typing import Anyimport click+from hogli import telemetryfrom hogli.manifest import get_manifestfrom . import mutagen@@ -740,6 +741,9 @@ def devbox_doctor() -> None:if not reachable:diagnosis = _diagnose_unreachable_coder()+ # doctor exits 0 while reporting a broken tailnet, so a failure count+ # off this property has to filter on command or exit_code.+ telemetry.add_command_properties(devbox_failure_cause=diagnosis.code)click.echo()click.echo(click.style(f" Cause: {diagnosis.cause}", fg="yellow"))click.echo(f" Next: {diagnosis.next_step}")diff --git a/tools/hogli-commands/hogli_commands/devbox/coder.py b/tools/hogli-commands/hogli_commands/devbox/coder.pyindex a919f250f9f5..2655d3511869 100644--- a/tools/hogli-commands/hogli_commands/devbox/coder.py+++ b/tools/hogli-commands/hogli_commands/devbox/coder.py@@ -27,6 +27,7 @@ from typing import Any, NoReturnimport clickimport requests+from hogli import telemetryfrom hogli.manifest import load_manifest_MACOS_TAILSCALE_CLI = "/Applications/Tailscale.app/Contents/MacOS/Tailscale"@@ -119,9 +120,15 @@ class CoderUserInfo(dict[str, str]):"""Normalized subset of Coder user fields used by hogli."""-def _fail(message: str) -> NoReturn:- """Print a short actionable error and exit."""+def _fail(message: str, *, cause: str | None = None) -> NoReturn:+ """Print a short actionable error and exit.++ ``cause`` is a stable slug recorded on the command's telemetry event.+ Without it every distinct failure reads as one undifferentiated error.+ """click.echo(click.style(message, fg="red"))+ if cause:+ telemetry.add_command_properties(devbox_failure_cause=cause)raise SystemExit(1)@@ -402,7 +409,8 @@ def ensure_tailscale_connected(setup_hint: str = RUNTIME_SETUP_HINT) -> None:"Tailscale is not installed.\n"f" {_tailscale_install_hint()}\n"f" See {_TAILSCALE_RUNBOOK_URL} for joining the PostHog tailnet.\n"- f" Then {setup_hint}"+ f" Then {setup_hint}",+ cause="tailscale_not_installed",)# CLI is resolvable, but the daemon is not running -- the user needs to@@ -417,14 +425,16 @@ def ensure_tailscale_connected(setup_hint: str = RUNTIME_SETUP_HINT) -> None:" To use the CLI from your shell, symlink it once:\n"f" sudo ln -sfn {_MACOS_TAILSCALE_CLI} /usr/local/bin/tailscale\n"f" See {_TAILSCALE_RUNBOOK_URL} if you have not yet been added to the tailnet.\n"- f" Then {setup_hint}"+ f" Then {setup_hint}",+ cause="tailscale_not_connected_cli_missing",)_fail("Tailscale is installed but not connected.\n"f" {_tailscale_connect_hint()}\n"f" See {_TAILSCALE_RUNBOOK_URL} if you have not yet been added to the tailnet.\n"- f" Then {setup_hint}"+ f" Then {setup_hint}",+ cause="tailscale_not_connected",)@@ -448,6 +458,10 @@ def ensure_tailscale_routes_accepted() -> None:if _tailscale_routes_accepted():return+ # The fix below is silent, so without this the number of hosts that land+ # here stays unknowable.+ telemetry.add_command_properties(devbox_routes_were_off=True)+tailscale_path = _resolve_tailscale()if not tailscale_path:return@@ -460,7 +474,10 @@ def ensure_tailscale_routes_accepted() -> None:result = subprocess.run(cmd, env=_tailscale_env(tailscale_path))if result.returncode != 0:manual = "tailscale set --accept-routes" if sys.platform == "darwin" else "sudo tailscale set --accept-routes"- _fail(f"Failed to enable Tailscale subnet routes. Run manually: {manual}")+ _fail(+ f"Failed to enable Tailscale subnet routes. Run manually: {manual}",+ cause="accept_routes_failed",+ )def coder_reachable(timeout: float = 5.0) -> bool:@@ -481,8 +498,12 @@ class CoderReachabilityDiagnosis:fix rather than a list of commands the user has to interpret. ``facts``is a short list of diagnostic data (tailnet name, resolved IP, peerhealth) that is safe to share verbatim when asking for help.++ ``code`` is the same cause as a stable slug. ``cause`` interpolates+ hostnames and peer names, so it cannot be grouped on."""+ code: strcause: strnext_step: strfacts: list[str]@@ -542,6 +563,7 @@ def _diagnose_unreachable_coder() -> CoderReachabilityDiagnosis:if resolved_ip is None:facts.append(f"DNS for {host}: failed")return CoderReachabilityDiagnosis(+ code="dns_lookup_failed",cause=f"DNS lookup for {host} failed.",next_step=("MagicDNS may be off or you may be on the wrong tailnet. "@@ -555,6 +577,7 @@ def _diagnose_unreachable_coder() -> CoderReachabilityDiagnosis:if _tcp_reachable(host, 443):facts.append(f"TCP {host}:443: open")return CoderReachabilityDiagnosis(+ code="https_probe_failed",cause=f"TCP to {host}:443 works but the HTTPS probe failed.",next_step=("The Coder deployment may be restarting, or your system clock "@@ -591,6 +614,7 @@ def _diagnose_blocked_route(if not routers:return CoderReachabilityDiagnosis(+ code="no_subnet_routes_advertised",cause="No peer on your tailnet advertises subnet routes.",next_step=("Either you are not on the PostHog tailnet (check the name "@@ -604,6 +628,7 @@ def _diagnose_blocked_route(if not online_routers:names = ", ".join(str(p.get("HostName") or "?") for p in routers)return CoderReachabilityDiagnosis(+ code="subnet_router_offline",cause=f"Subnet router peer is offline ({names}).",next_step=("Wait a minute and retry. If it stays offline, reach out to Team DevEx — the relay likely needs a bounce."@@ -612,6 +637,7 @@ def _diagnose_blocked_route()return CoderReachabilityDiagnosis(+ code="tcp_blocked",cause="TCP is blocked despite an online subnet router on your tailnet.",next_step=("A non-Tailscale VPN or a local firewall is likely intercepting, "@@ -647,7 +673,7 @@ def ensure_coder_reachable() -> None:*(f" - {fact}" for fact in diagnosis.facts),])- _fail(body)+ _fail(body, cause=diagnosis.code)def _encode_ssh_option(value: str) -> str:@@ -830,7 +856,7 @@ def ensure_coder_authenticated() -> None:returnif not coder_installed():- _fail(f"`coder` is not installed. {RUNTIME_SETUP_HINT}")+ _fail(f"`coder` is not installed. {RUNTIME_SETUP_HINT}", cause="coder_not_installed")coder_url = get_coder_url()click.echo(f"Logging in to {coder_url}...")@@ -846,10 +872,10 @@ def ensure_runtime_ready() -> None:ensure_coder_reachable()if not coder_installed():- _fail(f"`coder` is not installed. {RUNTIME_SETUP_HINT}")+ _fail(f"`coder` is not installed. {RUNTIME_SETUP_HINT}", cause="coder_not_installed")if not coder_authenticated():- _fail(f"Coder login is not ready for {get_coder_url()}. {RUNTIME_SETUP_HINT}")+ _fail(f"Coder login is not ready for {get_coder_url()}. {RUNTIME_SETUP_HINT}", cause="coder_login_not_ready")_warn_version_mismatch()diff --git a/tools/hogli-commands/hogli_commands/devenv/cli.py b/tools/hogli-commands/hogli_commands/devenv/cli.pyindex ca86e81e94ad..c8878dfd8b1f 100644--- a/tools/hogli-commands/hogli_commands/devenv/cli.py+++ b/tools/hogli-commands/hogli_commands/devenv/cli.py@@ -6,6 +6,7 @@ Provides hogli dev:* commands for managing the development environment.from __future__ import annotationsimport click+from hogli import telemetryfrom .generator import (TRACKED_MPROCS_FILES,@@ -95,15 +96,12 @@ def dev_generate(generator.generate_and_save(resolved, output_path, saved_config)- # Stash devenv-specific properties so _fire_telemetry includes them- # in the command_completed event for dev:generate.- ctx = click.get_current_context()- ctx.meta["hogli.devenv"] = {- "intents": sorted(resolved.intents),- "intent_count": len(resolved.intents),- "unit_count": len(resolved.units),- "docker_profiles": sorted(resolved.docker_profiles),- }+ telemetry.add_command_properties(+ intents=sorted(resolved.intents),+ intent_count=len(resolved.intents),+ unit_count=len(resolved.units),+ docker_profiles=sorted(resolved.docker_profiles),+ )click.echo("Generated mprocs config from saved config")click.echo(f" Products: {', '.join(sorted(resolved.intents))}")diff --git a/tools/hogli-commands/hogli_commands/tests/test_devbox.py b/tools/hogli-commands/hogli_commands/tests/test_devbox.pyindex b6330e814336..4077ec764706 100644--- a/tools/hogli-commands/hogli_commands/tests/test_devbox.py+++ b/tools/hogli-commands/hogli_commands/tests/test_devbox.py@@ -34,6 +34,13 @@ def devbox_config_path(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> Path:return config_path+def recorded_properties(monkeypatch: pytest.MonkeyPatch) -> dict[str, object]:+ recorded: dict[str, object] = {}+ monkeypatch.setattr(coder.telemetry, "add_command_properties", lambda **props: recorded.update(props))+ return recorded++class TestDevboxConfig:"""Test persisted devbox preferences."""@@ -351,7 +358,9 @@ class TestTailscaleRoutesAccepted:)assert coder._tailscale_routes_accepted() is False- def test_ensure_noop_when_already_accepted(self, monkeypatch: pytest.MonkeyPatch) -> None:+ def test_ensure_noop_when_already_accepted(+ self, monkeypatch: pytest.MonkeyPatch, recorded_properties: dict[str, object]+ ) -> None:monkeypatch.setattr(coder, "_tailscale_routes_accepted", lambda: True)calls: list[list[str]] = []@@ -364,8 +373,11 @@ class TestTailscaleRoutesAccepted:coder.ensure_tailscale_routes_accepted()assert calls == []+ assert recorded_properties == {}- def test_ensure_invokes_tailscale_set_accept_routes(self, monkeypatch: pytest.MonkeyPatch) -> None:+ def test_ensure_invokes_tailscale_set_accept_routes(+ self, monkeypatch: pytest.MonkeyPatch, recorded_properties: dict[str, object]+ ) -> None:monkeypatch.setattr(coder, "_tailscale_routes_accepted", lambda: False)monkeypatch.setattr(coder, "_resolve_tailscale", lambda: coder._MACOS_TAILSCALE_CLI)monkeypatch.setattr(coder.sys, "platform", "darwin")@@ -380,6 +392,7 @@ class TestTailscaleRoutesAccepted:coder.ensure_tailscale_routes_accepted()assert captured == [[coder._MACOS_TAILSCALE_CLI, "set", "--accept-routes"]]+ assert recorded_properties == {"devbox_routes_were_off": True}class TestCoderConfig:@@ -558,6 +571,7 @@ class TestCoderReachable:self,monkeypatch: pytest.MonkeyPatch,capsys: pytest.CaptureFixture[str],+ recorded_properties: dict[str, object],) -> None:monkeypatch.setattr(coder, "get_coder_url", lambda: "https://coder.example.com")monkeypatch.setattr(coder, "coder_reachable", lambda: False)@@ -565,6 +579,7 @@ class TestCoderReachable:coder,"_diagnose_unreachable_coder",lambda: coder.CoderReachabilityDiagnosis(+ code="stubbed_code",cause="stubbed cause.",next_step="stubbed step.",facts=["fact: one"],@@ -579,6 +594,7 @@ class TestCoderReachable:assert "stubbed cause." in outassert "stubbed step." in outassert "fact: one" in out+ assert recorded_properties == {"devbox_failure_cause": "stubbed_code"}class TestDiagnoseUnreachableCoder:@@ -598,6 +614,7 @@ class TestDiagnoseUnreachableCoder:monkeypatch.setattr(coder, "_tcp_reachable", must_not_run)diagnosis = coder._diagnose_unreachable_coder()+ assert diagnosis.code == "dns_lookup_failed"assert "DNS lookup" in diagnosis.causeassert "MagicDNS" in diagnosis.next_stepassert "Tailscale tailnet: posthog.com" in diagnosis.facts@@ -608,6 +625,7 @@ class TestDiagnoseUnreachableCoder:monkeypatch.setattr(coder, "_tcp_reachable", lambda host, port, timeout=3.0: True)diagnosis = coder._diagnose_unreachable_coder()+ assert diagnosis.code == "https_probe_failed"assert "HTTPS probe" in diagnosis.causeassert "clock" in diagnosis.next_step.lower()@@ -621,6 +639,7 @@ class TestDiagnoseUnreachableCoder:monkeypatch.setattr(coder, "_tcp_reachable", lambda host, port, timeout=3.0: False)diagnosis = coder._diagnose_unreachable_coder()+ assert diagnosis.code == "no_subnet_routes_advertised"assert "No peer" in diagnosis.causeassert "Team DevEx" in diagnosis.next_step@@ -639,6 +658,7 @@ class TestDiagnoseUnreachableCoder:monkeypatch.setattr(coder, "_tcp_reachable", lambda host, port, timeout=3.0: False)diagnosis = coder._diagnose_unreachable_coder()+ assert diagnosis.code == "subnet_router_offline"assert "subnet-router-us" in diagnosis.causeassert "Wait a minute" in diagnosis.next_step@@ -657,6 +677,7 @@ class TestDiagnoseUnreachableCoder:monkeypatch.setattr(coder, "_tcp_reachable", lambda host, port, timeout=3.0: False)diagnosis = coder._diagnose_unreachable_coder()+ assert diagnosis.code == "tcp_blocked"assert "blocked" in diagnosis.cause.lower()assert "ACL" in diagnosis.next_step or "VPN" in diagnosis.next_step.upper()diff --git a/tools/hogli/README.md b/tools/hogli/README.mdindex ce2d97fb79fd..3bf151000e8b 100644--- a/tools/hogli/README.md+++ b/tools/hogli/README.md@@ -239,6 +239,14 @@ def env_props(command: str | None) -> dict[str, object]:register_telemetry_properties(env_props)```+A command can also stash properties for its own `command_completed` event, for context only that command knows:++```python+from hogli import telemetry++telemetry.add_command_properties(failure_cause="unreachable")+```+### Post-command hooksRun after every command completes, regardless of success. Good for contextual hints, cleanup, or notifications.diff --git a/tools/hogli/src/hogli/cli.py b/tools/hogli/src/hogli/cli.pyindex 003478da5485..2a7674a49cf7 100644--- a/tools/hogli/src/hogli/cli.py+++ b/tools/hogli/src/hogli/cli.py@@ -684,10 +684,7 @@ def _fire_telemetry(ctx: click.Context, exit_code: int) -> None:"has_extra_argv": ctx.meta.get("hogli.has_extra_argv", False),**_env_properties(command),}- # Merge devenv-specific properties (set by dev:generate)- devenv = ctx.meta.get("hogli.devenv")- if devenv:- props.update(devenv)+ props.update(ctx.meta.get(telemetry.COMMAND_PROPERTIES_META_KEY) or {})telemetry.track("command_completed", props)except Exception:passdiff --git a/tools/hogli/src/hogli/telemetry.py b/tools/hogli/src/hogli/telemetry.pyindex 427a1eb3bd13..9cac80cbd759 100644--- a/tools/hogli/src/hogli/telemetry.py+++ b/tools/hogli/src/hogli/telemetry.py@@ -44,6 +44,10 @@ _DEFAULT_HOST = "https://us.i.posthog.com"# suppress real local signal -- deliberately not listed here._CI_ENV_VARS = ("CI", "GITHUB_ACTIONS", "JENKINS_URL", "GITLAB_CI", "CIRCLECI", "BUILDKITE")+# Shared by the writer (:func:`add_command_properties`) and the reader in+# hogli.cli, which would otherwise drift on a literal.+COMMAND_PROPERTIES_META_KEY = "hogli.command_properties"+def is_ci() -> bool:"""True when any common CI provider's environment variable is present."""@@ -305,6 +309,20 @@ def track(event: str, properties: dict[str, Any] | None = None) -> None:_client.track(event, properties)+def add_command_properties(**properties: Any) -> None:+ """Attach properties to this invocation's ``command_completed`` event.++ Lets a command record context the framework cannot know, such as why it+ failed, on the same event that already carries the command name and the+ environment. A separate event would need a join to answer any question+ that mixes the two. No-ops outside a click invocation.+ """+ ctx = click.get_current_context(silent=True)+ if ctx is None:+ return+ ctx.meta.setdefault(COMMAND_PROPERTIES_META_KEY, {}).update(properties)++def flush(timeout: float = 2.0) -> None:_client.flush(timeout)diff --git a/tools/hogli/tests/test_telemetry.py b/tools/hogli/tests/test_telemetry.pyindex 4a5413097ad7..3145d43a721f 100644--- a/tools/hogli/tests/test_telemetry.py+++ b/tools/hogli/tests/test_telemetry.py@@ -8,9 +8,10 @@ from pathlib import Pathimport pytestfrom unittest.mock import patch+import clickfrom click.testing import CliRunnerfrom hogli import telemetry-from hogli.cli import _outcome, _should_track, cli+from hogli.cli import _fire_telemetry, _outcome, _should_track, cli_TELEMETRY_ENV_VARS = (# Every CI marker the gate checks must be cleared, otherwise the suite@@ -264,6 +265,23 @@ class TestInvokeTelemetry:mock_send.assert_not_called()+class TestCommandProperties:+ def test_stashed_properties_reach_command_completed(self, monkeypatch: pytest.MonkeyPatch):+ # Category lookup reads the consumer's manifest, which core tests stay off.+ monkeypatch.setattr("hogli.cli.get_category_for_command", lambda command: "core")+ ctx = click.Context(cli)+ ctx.invoked_subcommand = "quickstart"+ ctx.meta["hogli.telemetry_active"] = True+ with ctx:+ telemetry.add_command_properties(failure_cause="unreachable")++ with patch.object(telemetry._client, "track") as mock_track:+ _fire_telemetry(ctx, 1)++ props = mock_track.call_args.args[1]+ assert props["failure_cause"] == "unreachable"++def _patch_cli_manifest(monkeypatch: pytest.MonkeyPatch, command_config: dict | None) -> None:"""Point hogli.cli at a fake manifest whose every command has *command_config*.