Skip to content

Compress tool outputs, logs, files, and RAG chunks before they reach the LLM. 20% fewer tokens for coding agents, 60-95% fewer tokens for JSON, same answers. Library, proxy, MCP server.

fix(telemetry): let HEADROOM_TELEMETRY=off stop the anonymous beacon (#4235)

Tejas Chopra1a40b3ce67ad
diff --git a/README.md b/README.md
index a478cf7f8..adacc2f21 100644
--- a/README.md
+++ b/README.md
@@ -624,8 +624,8 @@ prompts, completions, code or file paths. It exists so we can see when a release
regresses a compression ratio across real workloads rather than only our own test
corpus.
-Turn it off with `HEADROOM_BEACON=off`, the `DO_NOT_TRACK=1` convention, or
-`HEADROOM_OFFLINE=1`. The full field list is in
+Turn it off with `HEADROOM_BEACON=off`, `HEADROOM_TELEMETRY=off`, the
+`DO_NOT_TRACK=1` convention, or `HEADROOM_OFFLINE=1`. The full field list is in
[the proxy docs](https://docs.headroomlabs.ai/docs/proxy).
## Headroom for teams
diff --git a/docs/content/docs/limitations.mdx b/docs/content/docs/limitations.mdx
index 2553a9d90..67c89b8e9 100644
--- a/docs/content/docs/limitations.mdx
+++ b/docs/content/docs/limitations.mdx
@@ -174,10 +174,12 @@ this page's "nothing leaves the machine" framing as universal:
compression ratios, skip reasons, provider and model ids, failure counts, plus
OS and architecture. Never prompts, completions, code, or file paths -- the
collector allowlists fields server-side and drops the rest. Disable it with
- `HEADROOM_BEACON=off`, the cross-tool `DO_NOT_TRACK=1` convention, or by
+ `HEADROOM_BEACON=off`, `HEADROOM_TELEMETRY=off`, the cross-tool `DO_NOT_TRACK=1` convention, or by
running offline. `is_beacon_enabled()` is fail-open: an unrecognized value
uploads rather than staying silent. See [Proxy](/docs/proxy) for the full
field list.
These are deliberately separate so that enabling local `/stats` does not
-silently start an upload on the next release.
+silently start an upload on the next release. The one crossing only ever turns
+the upload off: an explicit `HEADROOM_TELEMETRY=off` also stops the beacon
+(unless `HEADROOM_BEACON=on`).
diff --git a/docs/content/docs/proxy.mdx b/docs/content/docs/proxy.mdx
index 7d49ed051..78955de6e 100644
--- a/docs/content/docs/proxy.mdx
+++ b/docs/content/docs/proxy.mdx
@@ -24,7 +24,7 @@ headroom proxy \
--budget 100.0
```
-Two independent telemetry switches exist. `HEADROOM_TELEMETRY=on` (or `--telemetry`) turns on **local-only** in-process usage stats that power your own `/stats`, `/metrics`, and dashboard — off by default, and nothing under this switch leaves the machine.
+Two telemetry switches exist. `HEADROOM_TELEMETRY=on` (or `--telemetry`) turns on **local-only** in-process usage stats that power your own `/stats`, `/metrics`, and dashboard — off by default, and nothing under this switch leaves the machine.
Separately, an **anonymous usage beacon is on by default** (opt-out). Once a session goes idle it POSTs a small summary of how compression behaved to a Headroom Labs collector.
@@ -36,7 +36,7 @@ Separately, an **anonymous usage beacon is on by default** (opt-out). Once a ses
The install id is a random UUID generated on first run and stored in your config directory. It is deliberately not derived from hostname, MAC address, or any hardware property — delete the file and you get a new one.
-Disable it with `HEADROOM_BEACON=off`, the `DO_NOT_TRACK=1` convention, or `HEADROOM_OFFLINE=1` (which also disables update checks and license reporting).
+Disable it with `HEADROOM_BEACON=off`, `HEADROOM_TELEMETRY=off` (or `--no-telemetry`), the `DO_NOT_TRACK=1` convention, or `HEADROOM_OFFLINE=1` (which also disables update checks and license reporting). `HEADROOM_BEACON=on` keeps the beacon on even with local stats off. `headroom telemetry` names the setting that turned it off.
## CLI options
diff --git a/docs/content/docs/security-model.mdx b/docs/content/docs/security-model.mdx
index 1ab994d81..729769887 100644
--- a/docs/content/docs/security-model.mdx
+++ b/docs/content/docs/security-model.mdx
@@ -343,7 +343,7 @@ Beyond your configured LLM providers, Headroom may contact:
| Destination | Purpose | Default | Disable / pre-provision |
|---|---|---|---|
-| `headroom-beacon.headroom-beacon.workers.dev` | Anonymous session summaries to Headroom Labs | **On** — see [The beacon](#the-beacon-is-on-by-default) | `HEADROOM_BEACON=off`, `DO_NOT_TRACK=1`, or `HEADROOM_OFFLINE` |
+| `headroom-beacon.headroom-beacon.workers.dev` | Anonymous session summaries to Headroom Labs | **On** — see [The beacon](#the-beacon-is-on-by-default) | `HEADROOM_BEACON=off`, `HEADROOM_TELEMETRY=off`, `DO_NOT_TRACK=1`, or `HEADROOM_OFFLINE` |
| `pypi.org` | Daily version check for update notices | On | `HEADROOM_UPDATE_CHECK=off`; also skipped in `--stateless`, in CI, and from source checkouts |
| `huggingface.co` | Downloads models for the optional ML compression paths | On first use of those features | Pre-provision the model cache, or leave the features disabled |
| `app.headroomlabs.ai` | License validation and usage reporting | Only with a license key configured | Omit the license key |
@@ -379,14 +379,17 @@ Prompts, completions, file contents, tool results, and file paths are **not** in
payload. The install id is a random UUID rather than a machine fingerprint, and resets
if you delete `<config dir>/install_id`.
-Three controls switch it off, checked in this order:
+Four controls switch it off, checked in this order:
```bash
-HEADROOM_OFFLINE=1 # offline mode — disables all egress, not just the beacon
-DO_NOT_TRACK=1 # the cross-tool convention, honoured
-HEADROOM_BEACON=off # also false / 0 / no / disable / disabled
+HEADROOM_OFFLINE=1 # offline mode — disables all egress, not just the beacon
+DO_NOT_TRACK=1 # the cross-tool convention, honoured
+HEADROOM_BEACON=off # also false / 0 / no / disable / disabled; =on keeps it on
+HEADROOM_TELEMETRY=off # same off-values; also what --no-telemetry sets
```
+`headroom telemetry` names the setting that turned it off.
+
The destination can also be redirected with `HEADROOM_TELEMETRY_ENDPOINT`, which is
useful if you would rather terminate the reports at a receiver you control than block
them outright.
@@ -401,8 +404,8 @@ assuming a typo fails safe.
`HEADROOM_TELEMETRY` is a **different switch**, off by default and opt-in. It aggregates
stats locally for the in-process collector and the `/stats` and `/v1/telemetry`
-endpoints, and sends nothing off-host. Enabling it does not authorise beacon upload, and
-disabling it does not suppress the beacon — the two are deliberately independent.
+endpoints, and sends nothing off-host. Enabling it does not authorise beacon upload; an
+explicit `HEADROOM_TELEMETRY=off` does suppress the beacon, unless `HEADROOM_BEACON=on`.
Operational metrics are separate again: OpenTelemetry export
(`HEADROOM_OTEL_METRICS_*`) is opt-in and targets a collector you specify.
diff --git a/headroom/cli/install.py b/headroom/cli/install.py
index 870b53c24..659e11182 100644
--- a/headroom/cli/install.py
+++ b/headroom/cli/install.py
@@ -604,7 +604,8 @@ def _build_deployment_manifest(
region=region,
proxy_mode=proxy_mode,
memory_enabled=memory,
- telemetry_enabled=telemetry and not no_telemetry,
+ # --no-telemetry wins when both are given; neither leaves it unset.
+ telemetry_enabled=False if no_telemetry else (True if telemetry else None),
no_rate_limit=no_rate_limit,
image=image,
no_http2=no_http2,
@@ -875,7 +876,7 @@ def _echo_installed(manifest: DeploymentManifest, *, prefix: str = "Installed pe
@click.option(
"--no-telemetry",
is_flag=True,
- help="Force anonymous telemetry off in the runtime (already the default).",
+ help="Turn off local stats and the anonymous upload beacon in the runtime.",
)
@click.option(
"--no-rate-limit",
@@ -1092,7 +1093,7 @@ def install_apply(
@click.option(
"--no-telemetry",
is_flag=True,
- help="Force anonymous telemetry off in the runtime (already the default).",
+ help="Turn off local stats and the anonymous upload beacon in the runtime.",
)
@click.option(
"--image",
diff --git a/headroom/cli/proxy.py b/headroom/cli/proxy.py
index 6ae7848be..801ef8499 100644
--- a/headroom/cli/proxy.py
+++ b/headroom/cli/proxy.py
@@ -1112,7 +1112,7 @@ def dashboard(port: int, no_open: bool) -> None:
@click.option(
"--no-telemetry",
is_flag=True,
- help="Force anonymous usage telemetry off (already the default; env: HEADROOM_TELEMETRY=off)",
+ help="Turn off local stats and the anonymous upload beacon (env: HEADROOM_TELEMETRY=off)",
)
@click.option(
"--stateless",
diff --git a/headroom/cli/telemetry.py b/headroom/cli/telemetry.py
index e68e85aad..452a4fa0e 100644
--- a/headroom/cli/telemetry.py
+++ b/headroom/cli/telemetry.py
@@ -85,7 +85,7 @@ def telemetry(show: bool, as_json: bool) -> None:
headroom telemetry Current state and the two switches
headroom telemetry --show The exact payload, field by field
"""
- from headroom.telemetry.beacon import is_beacon_enabled, is_telemetry_enabled
+ from headroom.telemetry.beacon import beacon_off_reason, is_telemetry_enabled
from headroom.telemetry.session import (
DEFAULT_ENDPOINT,
SCHEMA_VERSION,
@@ -94,7 +94,8 @@ def telemetry(show: bool, as_json: bool) -> None:
resource_attributes,
)
- beacon_on = is_beacon_enabled()
+ beacon_off_by = beacon_off_reason()
+ beacon_on = beacon_off_by is None
local_on = is_telemetry_enabled()
known_id = read_install_id()
# Reported because it changes what goes on the wire, and because while the
@@ -134,7 +135,7 @@ def telemetry(show: bool, as_json: bool) -> None:
)
return
- click.echo(f"Upload beacon: {'ON (opt-out)' if beacon_on else 'OFF'}")
+ click.echo(f"Upload beacon: {'ON (opt-out)' if beacon_on else f'OFF ({beacon_off_by})'}")
click.echo(f"Local stats: {'ON' if local_on else 'OFF (opt-in)'}")
click.echo(f"Endpoint: {DEFAULT_ENDPOINT}")
click.echo(
@@ -143,5 +144,8 @@ def telemetry(show: bool, as_json: bool) -> None:
)
click.echo(f"Install ID: {known_id or '(none yet — created on first upload)'}")
click.echo()
- click.echo("Turn the beacon off: HEADROOM_BEACON=off (or DO_NOT_TRACK=1)")
+ if beacon_on:
+ click.echo(
+ "Turn the beacon off: HEADROOM_BEACON=off (or HEADROOM_TELEMETRY=off, DO_NOT_TRACK=1)"
+ )
click.echo("See the exact payload: headroom telemetry --show")
diff --git a/headroom/dashboard/templates/dashboard.html b/headroom/dashboard/templates/dashboard.html
index 2b449a7af..403d9a80b 100644
--- a/headroom/dashboard/templates/dashboard.html
+++ b/headroom/dashboard/templates/dashboard.html
@@ -152,7 +152,7 @@
</div>
<template x-if="stats.anon_telemetry_shipping">
<div class="inline-flex items-center gap-1.5 rounded-full border border-amber-500/40 bg-amber-500/10 px-2.5 py-1"
- title="The anonymous telemetry beacon is on: compression stats only, never prompts, code, or file paths. Turn it off with HEADROOM_BEACON=off or DO_NOT_TRACK=1.">
+ title="The anonymous telemetry beacon is on: compression stats only, never prompts, code, or file paths. Turn it off with HEADROOM_BEACON=off, HEADROOM_TELEMETRY=off or DO_NOT_TRACK=1.">
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16" fill="currentColor" aria-hidden="true"
class="w-3 h-3 text-amber-400 shrink-0">
<path fill-rule="evenodd"
diff --git a/headroom/install/models.py b/headroom/install/models.py
index a502d74f8..19939bf1f 100644
--- a/headroom/install/models.py
+++ b/headroom/install/models.py
@@ -106,7 +106,9 @@ class DeploymentManifest:
proxy_mode: str = "cache"
memory_enabled: bool = False
memory_db_path: str = ""
- telemetry_enabled: bool = True
+ # None: the operator chose neither --telemetry nor --no-telemetry. The
+ # default stays True for manifests saved before the field existed.
+ telemetry_enabled: bool | None = True
image: str = "ghcr.io/headroomlabs-ai/headroom:latest"
service_name: str = "headroom"
container_name: str = "headroom-persistent"
diff --git a/headroom/install/planner.py b/headroom/install/planner.py
index 4c55c2567..db75fc027 100644
--- a/headroom/install/planner.py
+++ b/headroom/install/planner.py
@@ -150,7 +150,7 @@ def build_manifest(
region: str | None,
proxy_mode: str,
memory_enabled: bool,
- telemetry_enabled: bool,
+ telemetry_enabled: bool | None,
image: str,
no_rate_limit: bool = False,
no_http2: bool = False,
@@ -201,9 +201,12 @@ def build_manifest(
base_env["HEADROOM_ANYLLM_PROVIDER"] = anyllm_provider
if region:
base_env["HEADROOM_REGION"] = region
- # Telemetry is opt-in (off by default). Write the value explicitly so the
- # generated manifest is unambiguous and doesn't depend on the runtime default.
- base_env["HEADROOM_TELEMETRY"] = "on" if telemetry_enabled else "off"
+ # Write the operator's explicit choice only. ``off`` also stops the upload
+ # beacon (telemetry/beacon.py), so writing it by default would turn the
+ # beacon off for every install nobody asked to opt out. Local stats stay
+ # off without it: they are opt-in.
+ if telemetry_enabled is not None:
+ base_env["HEADROOM_TELEMETRY"] = "on" if telemetry_enabled else "off"
if memory_enabled:
base_env["HEADROOM_MEMORY_ENABLED"] = "1"
# Grok / Grok Build need proxy upstream = xAI. Only auto-set when no other
@@ -262,7 +265,8 @@ def build_manifest(
"--backend",
backend,
]
- proxy_args.append("--telemetry" if telemetry_enabled else "--no-telemetry")
+ if telemetry_enabled is not None:
+ proxy_args.append("--telemetry" if telemetry_enabled else "--no-telemetry")
# Agentic CLI targets (Claude Code, Codex) burst well above 60 req/min.
# Persist the flag so reinstalls don't silently reintroduce throttling.
# (see: https://github.com/headroomlabs-ai/headroom/issues/1350)
diff --git a/headroom/proxy/server.py b/headroom/proxy/server.py
index 0edd8e1c5..b910f4257 100644
--- a/headroom/proxy/server.py
+++ b/headroom/proxy/server.py
@@ -202,7 +202,7 @@ from headroom.subscription.tracker import (
get_subscription_tracker,
)
from headroom.telemetry import get_telemetry_collector
-from headroom.telemetry.beacon import is_beacon_enabled, is_telemetry_enabled
+from headroom.telemetry.beacon import beacon_off_reason, is_beacon_enabled, is_telemetry_enabled
from headroom.telemetry.toin import get_toin
from headroom.transforms import (
CacheAligner,
@@ -2376,10 +2376,11 @@ class HeadroomProxy(
if is_beacon_enabled():
logger.info(
"Anonymous upload beacon: ENABLED (default — session summaries are sent to "
- "Headroom Labs). Opt out: HEADROOM_BEACON=off or DO_NOT_TRACK=1"
+ "Headroom Labs). Opt out: HEADROOM_BEACON=off, HEADROOM_TELEMETRY=off or "
+ "DO_NOT_TRACK=1"
)
else:
- logger.info("Anonymous upload beacon: DISABLED")
+ logger.info("Anonymous upload beacon: DISABLED (%s)", beacon_off_reason())
self.pipeline_extensions.emit(
PipelineStage.POST_START,
diff --git a/headroom/telemetry/beacon.py b/headroom/telemetry/beacon.py
index 72556e761..f23c0e70e 100644
--- a/headroom/telemetry/beacon.py
+++ b/headroom/telemetry/beacon.py
@@ -8,7 +8,8 @@ Never leaves the machine.
``HEADROOM_BEACON`` — **on by default, opt-out.** Uploads an anonymous,
content-free session summary to Headroom Labs. Disable with
-``HEADROOM_BEACON=off``, ``DO_NOT_TRACK=1``, or offline mode. See
+``HEADROOM_BEACON=off``, ``HEADROOM_TELEMETRY=off``, ``DO_NOT_TRACK=1``, or
+offline mode. See
:mod:`headroom.telemetry.session` for the exact payload and
``deploy/beacon/worker.js`` for what the receiver does with it.
@@ -17,7 +18,9 @@ collector via ``HEADROOM_OTEL_METRICS_*`` — a destination you control, that
Headroom Labs never sees.
Keeping these separate matters: an operator who turned on local stats has not
-thereby agreed to upload anything, and must not start doing so on upgrade.
+thereby agreed to upload anything, and must not start doing so on upgrade. The
+one crossing is deliberate and only ever turns the upload off: an explicit
+``HEADROOM_TELEMETRY=off`` reads as "send nothing", so the beacon honours it.
"""
from __future__ import annotations
@@ -56,40 +59,53 @@ def is_telemetry_enabled() -> bool:
BEACON_DEFAULT_ON = True
-def is_beacon_enabled() -> bool:
- """Check if the anonymous upload beacon is enabled.
+def beacon_off_reason() -> str | None:
+ """Name the setting that turns the anonymous upload beacon off, or ``None`` when on.
- Default is :data:`BEACON_DEFAULT_ON`. Three things switch it off regardless,
- in this order:
+ Default is :data:`BEACON_DEFAULT_ON`. Checked in this order, first match wins:
* offline mode — no network is no network;
* ``DO_NOT_TRACK`` — the cross-tool convention, honoured because a user who
has already stated this preference should not have to state it again;
- * ``HEADROOM_BEACON=off`` (or false/0/no/disable/disabled).
-
- Deliberately a *separate* switch from ``HEADROOM_TELEMETRY``. That flag
- means "aggregate stats locally so ``/stats`` has something to show" — data
- that never leaves the machine. Overloading it to also authorise upload
- would mean every operator who had turned on local stats begins transmitting
- the moment they upgrade, having answered a different question.
-
- Note the asymmetry with :func:`is_telemetry_enabled`, which is fail-closed:
- this one is fail-open by construction while ``BEACON_DEFAULT_ON`` is True,
- so an unrecognised value uploads rather than staying silent.
+ * ``HEADROOM_BEACON`` — the beacon's own switch; an explicit on-value keeps
+ the beacon on even when local stats are off;
+ * ``HEADROOM_TELEMETRY=off`` (or false/0/no/disable/disabled) — people set
+ the telemetry switch to mean "send nothing", so an explicit off stops the
+ upload too.
+
+ Only an explicit *off* on ``HEADROOM_TELEMETRY`` reaches the beacon. Its
+ *on* still means only "aggregate stats locally": turning on local stats must
+ never be read as agreeing to upload.
+
+ The result is what ``headroom telemetry`` prints, so it is the variable and
+ value as the operator wrote them (lowercased), e.g. ``HEADROOM_TELEMETRY=off``.
"""
- from headroom.offline import is_offline
+ from headroom.offline import OFFLINE_ENV, is_offline
if is_offline():
- return False
+ return f"{OFFLINE_ENV} (offline mode)"
dnt = os.environ.get("DO_NOT_TRACK", "").lower().strip()
if dnt and dnt not in _OFF_VALUES:
- return False
+ return f"DO_NOT_TRACK={dnt}"
raw = os.environ.get("HEADROOM_BEACON", "").lower().strip()
if raw in _OFF_VALUES:
- return False
+ return f"HEADROOM_BEACON={raw}"
if raw in _ON_VALUES:
- return True
- return BEACON_DEFAULT_ON
+ return None
+ local = os.environ.get("HEADROOM_TELEMETRY", "").lower().strip()
+ if local in _OFF_VALUES:
+ return f"HEADROOM_TELEMETRY={local}"
+ return None if BEACON_DEFAULT_ON else "default (opt-in)"
+
+
+def is_beacon_enabled() -> bool:
+ """Check if the anonymous upload beacon is enabled; see :func:`beacon_off_reason`.
+
+ Note the asymmetry with :func:`is_telemetry_enabled`, which is fail-closed:
+ this one is fail-open by construction while ``BEACON_DEFAULT_ON`` is True,
+ so an unrecognised value uploads rather than staying silent.
+ """
+ return beacon_off_reason() is None
def is_telemetry_warn_enabled() -> bool:
diff --git a/headroom/telemetry/session.py b/headroom/telemetry/session.py
index 3a1cd9175..ccfb9f82e 100644
--- a/headroom/telemetry/session.py
+++ b/headroom/telemetry/session.py
@@ -1768,7 +1768,13 @@ def post_session_event(payload: dict[str, Any]) -> None:
ponytail: unbounded thread spawn is safe only because the close rate is
bounded by the idle timeout. Revisit if anything else starts emitting here.
"""
+ from headroom.telemetry.beacon import is_beacon_enabled
+
try:
+ # Re-checked at send time: a session buffered before an opt-out must
+ # not upload after it (heartbeats and idle closes send through here).
+ if not is_beacon_enabled():
+ return
threading.Thread(
target=_post_blocking,
args=(payload,),
@@ -1812,9 +1818,17 @@ def _flush_at_exit() -> None:
Still does not cover SIGKILL or a closed laptop. Heartbeats bound the loss
there to one flush interval.
"""
+ from headroom.telemetry.beacon import is_beacon_enabled
+
aggregator = _aggregator
if aggregator is None:
return
+ try:
+ if not is_beacon_enabled(): # opted out since the session was buffered
+ return
+ except Exception:
+ logger.debug("telemetry: beacon gate failed at exit", exc_info=True)
+ return
aggregator.flush_all(emit=lambda payload: _post_blocking(payload, timeout=_EXIT_POST_TIMEOUT_S))
diff --git a/tests/test_install/test_planner.py b/tests/test_install/test_planner.py
index 2a4aca030..b7fd55e51 100644
--- a/tests/test_install/test_planner.py
+++ b/tests/test_install/test_planner.py
@@ -56,6 +56,44 @@ def test_build_manifest_for_persistent_docker_sets_expected_defaults() -> None:
assert "HEADROOM_KOMPRESS_BACKEND" not in manifest.base_env
+ ("telemetry", "no_telemetry", "env", "flag"),
+ [
+ (False, False, None, None),
+ (True, False, "on", "--telemetry"),
+ (False, True, "off", "--no-telemetry"),
+ (True, True, "off", "--no-telemetry"),
+ ],
+)
+def test_install_writes_telemetry_only_when_chosen(telemetry, no_telemetry, env, flag) -> None:
+ """``HEADROOM_TELEMETRY=off`` now stops the upload beacon, so an install with
+ no telemetry flag must not write it (or ``--no-telemetry``) by default."""
+ from headroom.cli.install import _build_deployment_manifest
+
+ manifest = _build_deployment_manifest(
+ preset=InstallPreset.PERSISTENT_DOCKER.value,
+ runtime="docker",
+ scope="user",
+ provider_mode="manual",
+ targets=(),
+ profile="default",
+ port=8787,
+ backend="anthropic",
+ anyllm_provider=None,
+ region=None,
+ proxy_mode="token",
+ memory=False,
+ telemetry=telemetry,
+ no_telemetry=no_telemetry,
+ image="ghcr.io/headroomlabs-ai/headroom:latest",
+ no_http2=False,
+ )
+
+ assert manifest.base_env.get("HEADROOM_TELEMETRY") == env
+ flags = {"--telemetry", "--no-telemetry"} & set(manifest.proxy_args)
+ assert flags == ({flag} if flag else set())
+
+
def test_build_manifest_docker_runtime_never_installs_native_supervisor() -> None:
manifest = build_manifest(
profile="default",
diff --git a/tests/test_telemetry_warning.py b/tests/test_telemetry_warning.py
index 2b78fd535..551b94e56 100644
--- a/tests/test_telemetry_warning.py
+++ b/tests/test_telemetry_warning.py
@@ -8,6 +8,7 @@ Covers:
- /stats endpoint exposes anon_telemetry_shipping flag
"""
+from types import SimpleNamespace
from unittest.mock import patch
import pytest
@@ -17,6 +18,7 @@ from click.testing import CliRunner # noqa: E402
from headroom.telemetry.beacon import ( # noqa: E402
format_telemetry_notice,
+ is_beacon_enabled,
is_telemetry_warn_enabled,
)
@@ -43,6 +45,53 @@ class TestIsTelemetryWarnEnabled:
assert is_telemetry_warn_enabled() is True
[email protected]("value", ["off", "OFF", "false", "0", "no", "disable", "disabled"])
+def test_telemetry_off_turns_the_beacon_off_and_says_so(monkeypatch, value):
+ """``HEADROOM_TELEMETRY=off`` means "send nothing": it used to leave the
+ upload beacon on, and only ``HEADROOM_BEACON=off`` stopped it."""
+ from headroom.cli.main import main
+
+ for var in ("HEADROOM_BEACON", "DO_NOT_TRACK", "HEADROOM_OFFLINE"):
+ monkeypatch.delenv(var, raising=False)
+ monkeypatch.setenv("HEADROOM_TELEMETRY", value)
+
+ assert is_beacon_enabled() is False
+ output = CliRunner().invoke(main, ["telemetry"]).output
+ assert f"Upload beacon: OFF (HEADROOM_TELEMETRY={value.lower()})" in output
+
+
+def test_buffered_session_is_not_sent_after_telemetry_off(monkeypatch):
+ """A session recorded while the beacon was on must not upload once the
+ operator opts out, at heartbeat/idle close or at exit."""
+ from headroom.telemetry import session as S
+
+ for var in ("HEADROOM_BEACON", "DO_NOT_TRACK", "HEADROOM_OFFLINE"):
+ monkeypatch.delenv(var, raising=False)
+ sent: list[dict] = []
+ monkeypatch.setattr(S, "_post_blocking", lambda payload, **kwargs: sent.append(payload))
+ aggregator = S.SessionAggregator(S.post_session_event, idle_s=900.0, flush_s=100.0)
+ monkeypatch.setattr(S, "_aggregator", aggregator)
+ outcome = SimpleNamespace(provider="openai", model="gpt-5.4", tokens_saved=10, tags={})
+ aggregator.record(outcome, now=1_000.0)
+ monkeypatch.setenv("HEADROOM_TELEMETRY", "off")
+
+ aggregator.record(outcome, now=1_150.0) # past flush_s: heartbeat
+ aggregator.record(outcome, now=3_000.0) # past idle_s: idle close
+ S._flush_at_exit()
+
+ assert sent == []
+
+
+def test_beacon_on_overrides_telemetry_off(monkeypatch):
+ """HEADROOM_BEACON is the beacon's own switch and still wins."""
+ for var in ("DO_NOT_TRACK", "HEADROOM_OFFLINE"):
+ monkeypatch.delenv(var, raising=False)
+ monkeypatch.setenv("HEADROOM_TELEMETRY", "off")
+ monkeypatch.setenv("HEADROOM_BEACON", "on")
+
+ assert is_beacon_enabled() is True
+
+
# ---------------------------------------------------------------------------
# format_telemetry_notice
# ---------------------------------------------------------------------------
@@ -228,28 +277,19 @@ class TestProxyCLITelemetryBanner:
assert "HEADROOM_TELEMETRY=off" in result.output or "--no-telemetry" in result.output
def test_banner_beacon_default_on_is_surfaced(self, runner, monkeypatch):
- """The actual bug: HEADROOM_TELEMETRY=off / --no-telemetry alone used
- to make the banner print a bare "Telemetry: DISABLED" even though the
- anonymous upload beacon (a separate, on-by-default switch) was still
- active and never mentioned. After the fix, an operator who sets only
- --no-telemetry still sees the beacon disclosed."""
- monkeypatch.setenv("HEADROOM_TELEMETRY", "off")
- monkeypatch.delenv("HEADROOM_BEACON", raising=False)
- monkeypatch.delenv("DO_NOT_TRACK", raising=False)
+ """With no switch set the banner discloses the opt-out beacon rather than
+ printing a bare "Telemetry: DISABLED" for the local-stats switch alone."""
+ for var in ("HEADROOM_TELEMETRY", "HEADROOM_BEACON", "DO_NOT_TRACK"):
+ monkeypatch.delenv(var, raising=False)
from headroom.cli.main import main
with patch("headroom.proxy.server.run_server", side_effect=SystemExit(0)):
- result = runner.invoke(main, ["proxy", "--no-telemetry"])
+ result = runner.invoke(main, ["proxy"])
assert "Telemetry:" in result.output
assert "usage counters" in result.output
assert "HEADROOM_BEACON=off" in result.output
- # The old banner's bare "DISABLED" claim must not appear on the
- # Telemetry line specifically (the banner has an unrelated
- # "Memory: DISABLED" line that must not make this assertion a
- # false pass) -- that combination is exactly the false assurance
- # this fix removes.
telemetry_line = next(
line for line in result.output.splitlines() if line.strip().startswith("Telemetry:")
)