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.
Python agentaianthropicclaude-codecompressioncontext-engineeringcontext-windowcursorfastapilangchainllmmcpopenaiprompt-engineeringproxypythonragtoken-optimizationtokenstypescript
fix(privacy): turn off ONNX Runtime's Microsoft telemetry by default (#4602)
Kenneth Wong31f1304026a9
diff --git a/crates/headroom-core/src/transforms/magika_detector.rs b/crates/headroom-core/src/transforms/magika_detector.rsindex 0150b337e..5806fc3d2 100644--- a/crates/headroom-core/src/transforms/magika_detector.rs+++ b/crates/headroom-core/src/transforms/magika_detector.rs@@ -154,10 +154,32 @@ fn init_ort_from_path(path: &Path) -> Result<(), String> {path.display())})?;- let _committed = builder.commit();+ // `ort` enables ONNX Runtime's usage telemetry by default, and ORT 1.31++ // uploads it to Microsoft on Linux and macOS too. Importing `headroom`+ // sets ORT_DISABLE_TELEMETRY, which stops the uploader before it starts;+ // this only stops later events, for Rust-only callers that skip Python.+ let enable = ort_telemetry_opted_in(std::env::var("ORT_DISABLE_TELEMETRY").ok().as_deref());+ let _committed = builder.with_telemetry(enable).commit();Ok(())}+/// Whether the caller explicitly allowed ONNX Runtime telemetry.+///+/// Mirrors the Python default (`headroom._ort.disable_ort_telemetry_by_default`):+/// off unless `ORT_DISABLE_TELEMETRY` is set to a value ORT itself does not+/// treat as "disabled" (ORT disables on `1`/`true`/`yes`/`on`/`y`, case- and+/// space-insensitive). So `ORT_DISABLE_TELEMETRY=0` turns it on for Rust-loaded+/// models exactly as it does for Python ones, and unset stays off.+fn ort_telemetry_opted_in(value: Option<&str>) -> bool {+ match value {+ None => false,+ Some(raw) => !matches!(+ raw.trim().to_ascii_lowercase().as_str(),+ "1" | "true" | "yes" | "on" | "y"+ ),+ }+}+fn discover_onnxruntime_libraries() -> Vec<PathBuf> {let mut roots = Vec::new();@@ -505,6 +527,17 @@ pub fn map_magika_label(label: &str) -> ContentType {mod tests {use super::*;+ #[test]+ fn ort_telemetry_stays_off_unless_explicitly_allowed() {+ assert!(!ort_telemetry_opted_in(None), "unset must stay off");+ for disabled in ["1", "true", "TRUE", " yes ", "on", "Y"] {+ assert!(!ort_telemetry_opted_in(Some(disabled)), "{disabled:?}");+ }+ for allowed in ["0", "false", "no", "off", ""] {+ assert!(ort_telemetry_opted_in(Some(allowed)), "{allowed:?}");+ }+ }+fn assert_detect(content: &str, expected: ContentType, hint: &str) {if let Err(init_reason) = magika_runtime_available_for_session_init() {// On hosts where Magika cannot safely initialize, assert gracefuldiff --git a/docs/content/docs/security-model.mdx b/docs/content/docs/security-model.mdxindex 58451ba0b..fecc9ea2c 100644--- a/docs/content/docs/security-model.mdx+++ b/docs/content/docs/security-model.mdx@@ -349,6 +349,7 @@ Beyond your configured LLM providers, Headroom may contact:| `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 |+| `mobile.events.data.microsoft.com` | ONNX Runtime's own usage telemetry to Microsoft (ORT 1.31+ on Linux and macOS): hashed device id, model file and graph names, model hashes, execution providers, hardware ids | **Off**: importing `headroom` sets `ORT_DISABLE_TELEMETRY=1` unless it is already set | Leave `ORT_DISABLE_TELEMETRY` unset or `1`; setting it to `0` turns ORT's telemetry back on |### The beacon is on by defaultdiff --git a/headroom/__init__.py b/headroom/__init__.pyindex 38cb05a06..eba825f65 100644--- a/headroom/__init__.py+++ b/headroom/__init__.py@@ -73,10 +73,15 @@ from __future__ import annotationsfrom importlib import import_modulefrom typing import Any-from ._ort import ensure_ort_dylib_pinned+from ._ort import disable_ort_telemetry_by_default, ensure_ort_dylib_pinnedfrom ._version import __version__ # noqa: F401from .offline import pin_litellm_cost_map_local+# Must run before any ONNX Runtime initializes (Python package or the Rust+# core's dylib): ORT reads ORT_DISABLE_TELEMETRY once, at startup, and+# otherwise uploads usage telemetry to Microsoft. See `headroom/_ort.py`.+disable_ort_telemetry_by_default()+# Must run before anything can import `headroom._core`: on Windows the# Rust core resolves onnxruntime.dll at runtime (ort load-dynamic), and# the bare DLL search lands on the Windows ML System32 build, whichdiff --git a/headroom/_ort.py b/headroom/_ort.pyindex 8f10cd7bd..97736eaa5 100644--- a/headroom/_ort.py+++ b/headroom/_ort.py@@ -45,6 +45,25 @@ from pathlib import Pathlogger = logging.getLogger(__name__)+_TELEMETRY_ENV_VAR = "ORT_DISABLE_TELEMETRY"+++def disable_ort_telemetry_by_default() -> None:+ """Opt ONNX Runtime out of Microsoft's usage telemetry unless the caller chose.++ Since 1.31, ONNX Runtime's Linux and macOS builds upload 1DS telemetry to+ ``mobile.events.data.microsoft.com`` by default: a hashed device id kept in+ ``~/Library/Application Support/Microsoft/DeveloperTools`` (macOS) plus, per+ session, the model file and graph names, model hashes, execution providers+ and hardware ids. ORT reads ``ORT_DISABLE_TELEMETRY`` once, when each copy+ of the runtime initializes (the Python package and the dylib the Rust core+ loads are separate copies), so this has to run before either can start.++ ``setdefault`` keeps an explicit caller value, including ``0`` to allow it.+ """+ os.environ.setdefault(_TELEMETRY_ENV_VAR, "1")++_ENV_VAR = "ORT_DYLIB_PATH"_MIN_RUST_ORT_API_VERSION = (1, 24)diff --git a/tests/test_transforms/test_ort_dylib.py b/tests/test_transforms/test_ort_dylib.pyindex 405db1df2..bb6c5aa55 100644--- a/tests/test_transforms/test_ort_dylib.py+++ b/tests/test_transforms/test_ort_dylib.py@@ -10,7 +10,11 @@ monkeypatched so every branch runs on any CI OS.from __future__ import annotations+import json+import os+import subprocessimport sys+import textwrapfrom types import SimpleNamespaceimport pytest@@ -157,3 +161,42 @@ def test_never_raises(monkeypatch):monkeypatch.setattr(_ort.importlib.util, "find_spec", boom)assert _ort.ensure_ort_dylib_pinned() is Noneassert "ORT_DYLIB_PATH" not in _ort.os.environ+++# ---- ORT_DISABLE_TELEMETRY default ----------------------------------------+++def test_telemetry_disabled_by_default(monkeypatch):+ monkeypatch.delenv("ORT_DISABLE_TELEMETRY", raising=False)+ _ort.disable_ort_telemetry_by_default()+ assert _ort.os.environ["ORT_DISABLE_TELEMETRY"] == "1"+++def test_telemetry_choice_of_caller_wins(monkeypatch):+ monkeypatch.setenv("ORT_DISABLE_TELEMETRY", "0")+ _ort.disable_ort_telemetry_by_default()+ assert _ort.os.environ["ORT_DISABLE_TELEMETRY"] == "0"+++def test_importing_headroom_disables_ort_telemetry_before_ort_loads():+ """ORT reads the variable once at startup, so it must be set at package import."""+ script = textwrap.dedent(+ """+ import json+ import os+ import sys++ import headroom++ print(json.dumps({+ "value": os.environ.get("ORT_DISABLE_TELEMETRY"),+ "ort_loaded": "onnxruntime" in sys.modules,+ }))+ """+ )+ env = {k: v for k, v in os.environ.items() if k != "ORT_DISABLE_TELEMETRY"}+ result = subprocess.run(+ [sys.executable, "-c", script], capture_output=True, text=True, check=True, env=env+ )+ data = json.loads(result.stdout.strip().splitlines()[-1])+ assert data == {"value": "1", "ort_loaded": False}