mirror of
https://github.com/headroomlabs-ai/headroom.git
synced 2026-11-22 15:10:00 +08:00
<!-- maintainer-current-main --> ## Maintainer latest-main checkpoint Published `fe40ae66e3d0dd9e7df00be81716c42370139004` incorporates upstream main `e4a60ed72f6ef5b28569f8bfbe2163cfda32c948`. 23 ORT/dylib/logging/Gemini tests pass; Ruff/format/diff pass. Main sync is clean; expected-fallback source changes remain only the two INFO log levels. Shared Gemini request-fixture repair is test-only. No new code finding. The inherited main shard-2 failure was confirmed in actual hosted logs and locally (four Gemini failures). This head carries the maintainer fixture repair: real ASGI Request/JSON bytes replace an unused body-reader mock. All six test-function ASTs/assertions are preserved; all 10 Gemini cases pass. Contributor production logic was not rewritten by the sync/fixture follow-up. Earlier runtime captures retain their original commit/platform scope. Fresh exact-head hosted qualification is requested; nothing merged by this review. <!-- /maintainer-current-main --> ## Description A plain `pip install headroom-ai` has no ONNX Runtime (it comes with `[proxy]`), and the pure-Python detector is the supported path there. The first `compress()` call still logged "Native content detection requires ONNX Runtime 1.24+; using pure-Python detection for this process" as a WARNING. Every library user sees it on first import; both coding agents in our sandbox runs saw it, and one spent a step investigating it before continuing. ## Type of Change - [x] Bug fix (non-breaking change that fixes an issue) ## Changes Made - `headroom/_ort.py`: the sibling "onnxruntime x.y exposes an older C API than Rust detection requires" message drops to INFO as well. It fires on Intel macOS, where the `proxy` extra pins `onnxruntime <1.24` by design (`docs/installation.mdx`: Rust ML detection stays disabled there), so a supported `[proxy]` install warned on first `compress()` too. Its test now asserts the level. - `headroom/transforms/content_router.py`: `logger.warning` to `logger.info` for the ORT-compat fallback, with a comment on why. The existing circuit breaker (`_detect_native_unhealthy`) already makes it fire once per process; unchanged. - `tests/test_transforms/test_ort_dylib.py::test_content_router_bypasses_native_detector_for_incompatible_ort`: now captures at INFO, asserts the record's level is INFO and that a second call logs nothing. ## Testing - [x] Unit tests: the test fails before the fix (`assert 30 == 20`) and passes after; `tests/test_transforms/test_ort_dylib.py` 10 passed. - [x] `ruff check` / `ruff format --check` ### Test Output ```text pytest tests/test_transforms/test_ort_dylib.py: 10 passed (fails before the fix: assert 30 == 20) source build, default logging: 20031 -> 95 FATAL kept: True (no fallback line on stderr) source build, INFO enabled: INFO headroom.transforms.content_router: Native content detection requires ONNX Runtime 1.24+; using pure-Python detection for this process. ``` ## Real Behavior Proof - Environment: macOS arm64, Python 3.12, clean venv with the published 0.42.0 wheel (no onnxruntime). - Exact command / steps: `HEADROOM_OFFLINE=1 python -c "from headroom import compress; ..."` on a 3,000-line log. - Observed result: the warning line on stderr on first import, then `20031 -> 95`. - After-fix, this branch built from source (`uv pip install -e .` with maturin, fresh venv with tiktoken, pydantic, filelock, opentelemetry-api; no onnxruntime): ```text headroom from /Users/tejas/headroom-wt-onnx-info/headroom/__init__.py 20031 -> 95 FATAL kept: True ``` No fallback line on stderr at default logging. With `logging.basicConfig(level=INFO)` the same run prints `INFO headroom.transforms.content_router: Native content detection requires ONNX Runtime 1.24+; using pure-Python detection for this process.` once. - Not tested: the native (ORT present) path, which this change does not touch. ## Runtime Rollout Safety - Rollout-managed feature(s): none; two log records change level from WARNING to INFO, no behaviour change - Minimum rollout channel: stable (ships with the next release) - Stable/default behavior changed: only log level; detection and compression paths are untouched - Kill switch / disable path: not needed; `HEADROOM_LOG_LEVEL`-style logger config still surfaces the line at INFO - Unsafe override required: no - Qualification impact: none - Rollback path: revert the commit ## Review Readiness - [x] I have performed a self-review - [x] This PR is ready for human review 🤖 Generated with [Claude Code](https://claude.com/claude-code) ## Maintainer post-merge revisit: maine9331b6bPublished `6d9b9a52ccb939fd6c404c1debe955ecda3af3a9` includes upstream main `e9331b6b963b5b6554f45943abed2366aaa25ea6`. 13 ORT runtime/dylib/logging tests passed. Clean main sync; the source change remains limited to expected fallback log levels, preserving fallback behavior and once-per-process behavior. Author source-built default/INFO evidence and latest discussion reconsidered; no new finding. Touched-file Ruff/format and whitespace checks pass. Contributor runtime logic was not rewritten. Scoped Windows tests use the existing development native extension; no fresh native build or installed-agent qualification is claimed. Hosted CI must finish on this exact head before reapproval. Nothing merged. ### Maintainer current-main requalification Exact head `7b7b3a1624c3e644f67b2ad9707c7e222ed2771c`, upstream main `ecbaf86d78cf52d185fbffa306157b9a4cc1b906`. Mechanically updated against upstream/mainecbaf86d78and re-reviewed the two expected ONNX-unavailable/older-API fallback records. Only severity changes to INFO; fallback behavior and once-per-process suppression remain intact. The test-only conflict retains main's two-chunk ASGI request helper and all memory assertions. No contributor production logic was rewritten. All 23 ORT/logging/Gemini tests pass; Ruff0.17.3 lint/format and whitespace checks pass. The author's source-built no-ORT default/INFO after-fix replay and its macOS scope were read and remain applicable; no new source-built runtime replay is claimed here. Local execution used the existing native extension. Formal approval awaits exact-head hosted qualification; maintainers handle those checks. Nothing merged. Exact-head hosted checks are being handled by maintainers. No new finding in the reviewed scope; formal approval awaits exact-head hosted qualification; nothing merged. --------- Co-authored-by: Claude Fable 5.1 <noreply@anthropic.com> Co-authored-by: JerrettDavis <mxjerrett@gmail.com>
217 lines
7.5 KiB
Python
217 lines
7.5 KiB
Python
"""Tests for headroom._ort -- the ORT_DYLIB_PATH auto-pin.
|
|
|
|
The resolver points the Rust core's ort-load-dynamic runtime at the pip
|
|
onnxruntime package's shared library on every platform: on Windows it
|
|
guards against the DLL search picking up the Windows ML System32
|
|
onnxruntime.dll, and on Linux/macOS it avoids static ORT import-time
|
|
CPU feature faults on older x86_64 CPUs (#1278). The platform is
|
|
monkeypatched so every branch runs on any CI OS.
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
import json
|
|
import logging
|
|
import os
|
|
import subprocess
|
|
import sys
|
|
import textwrap
|
|
from types import SimpleNamespace
|
|
|
|
import pytest
|
|
|
|
import headroom._ort as _ort
|
|
|
|
|
|
@pytest.fixture(autouse=True)
|
|
def _fresh_resolver(monkeypatch):
|
|
"""Reset the module-level cache and scrub the env before every test."""
|
|
monkeypatch.setattr(_ort, "_pinned", _ort._UNSET)
|
|
monkeypatch.setattr(_ort, "_pinned_from_override", False)
|
|
monkeypatch.setattr(_ort, "_installed_ort_version", lambda: (1, 24))
|
|
monkeypatch.delenv("ORT_DYLIB_PATH", raising=False)
|
|
|
|
|
|
def _force_windows(monkeypatch):
|
|
monkeypatch.setattr(sys, "platform", "win32")
|
|
|
|
|
|
def _fake_spec_for(monkeypatch, package_dir):
|
|
"""Make find_spec('onnxruntime') resolve to a fake package directory."""
|
|
spec = SimpleNamespace(origin=str(package_dir / "__init__.py"))
|
|
monkeypatch.setattr(
|
|
_ort.importlib.util,
|
|
"find_spec",
|
|
lambda name: spec if name == "onnxruntime" else None,
|
|
)
|
|
|
|
|
|
def test_pins_versioned_so_on_linux(monkeypatch, tmp_path):
|
|
monkeypatch.setattr(sys, "platform", "linux")
|
|
pkg = tmp_path / "onnxruntime"
|
|
capi = pkg / "capi"
|
|
capi.mkdir(parents=True)
|
|
so = capi / "libonnxruntime.so.1.22.0"
|
|
so.write_bytes(b"not really a shared object")
|
|
_fake_spec_for(monkeypatch, pkg)
|
|
|
|
assert _ort.ensure_ort_dylib_pinned() == str(so)
|
|
assert _ort.os.environ["ORT_DYLIB_PATH"] == str(so)
|
|
|
|
|
|
def test_pins_dylib_on_macos(monkeypatch, tmp_path):
|
|
monkeypatch.setattr(sys, "platform", "darwin")
|
|
pkg = tmp_path / "onnxruntime"
|
|
capi = pkg / "capi"
|
|
capi.mkdir(parents=True)
|
|
dylib = capi / "libonnxruntime.1.23.2.dylib"
|
|
dylib.write_bytes(b"not really a dylib")
|
|
_fake_spec_for(monkeypatch, pkg)
|
|
|
|
assert _ort.ensure_ort_dylib_pinned() == str(dylib)
|
|
assert _ort.os.environ["ORT_DYLIB_PATH"] == str(dylib)
|
|
|
|
|
|
def test_respects_existing_env(monkeypatch):
|
|
_force_windows(monkeypatch)
|
|
monkeypatch.setenv("ORT_DYLIB_PATH", r"C:\custom\onnxruntime.dll")
|
|
assert _ort.ensure_ort_dylib_pinned() == r"C:\custom\onnxruntime.dll"
|
|
assert _ort.os.environ["ORT_DYLIB_PATH"] == r"C:\custom\onnxruntime.dll"
|
|
assert _ort.rust_ort_runtime_compatible()
|
|
|
|
|
|
def test_incompatible_package_is_not_pinned(monkeypatch, tmp_path, caplog):
|
|
monkeypatch.setattr(_ort, "_installed_ort_version", lambda: (1, 23))
|
|
pkg = tmp_path / "onnxruntime"
|
|
capi = pkg / "capi"
|
|
capi.mkdir(parents=True)
|
|
(capi / "libonnxruntime.so.1.23.2").write_bytes(b"old")
|
|
_fake_spec_for(monkeypatch, pkg)
|
|
caplog.set_level(logging.INFO, logger=_ort.logger.name)
|
|
|
|
assert _ort.ensure_ort_dylib_pinned() is None
|
|
assert not _ort.rust_ort_runtime_compatible()
|
|
older = [r for r in caplog.records if "older C API" in r.getMessage()]
|
|
assert len(older) == 1
|
|
# Supported configuration (Intel macOS pins onnxruntime <1.24): not a warning.
|
|
assert older[0].levelno == logging.INFO
|
|
|
|
|
|
def test_content_router_bypasses_native_detector_for_incompatible_ort(monkeypatch, caplog):
|
|
import headroom.transforms.content_router as router
|
|
|
|
monkeypatch.setenv("HEADROOM_DETECT_BACKEND", "rust")
|
|
monkeypatch.setattr(_ort, "rust_ort_runtime_compatible", lambda: False)
|
|
monkeypatch.setattr(router, "_detect_native_unhealthy", False)
|
|
caplog.set_level(logging.INFO, logger=router.logger.name)
|
|
|
|
result = router._detect_content('{"safe": true}')
|
|
|
|
assert result.content_type.value.startswith("json")
|
|
assert router._detect_native_unhealthy is True
|
|
fallback = [r for r in caplog.records if "requires ONNX Runtime 1.24+" in r.getMessage()]
|
|
assert len(fallback) == 1
|
|
# A base install has no ONNX Runtime by design; the fallback is the
|
|
# supported path there, so it must not surface as a warning on first import.
|
|
assert fallback[0].levelno == logging.INFO
|
|
|
|
caplog.clear()
|
|
router._detect_content('{"safe": true}')
|
|
assert "requires ONNX Runtime 1.24+" not in caplog.text
|
|
|
|
|
|
def test_pins_to_package_capi_dll(monkeypatch, tmp_path):
|
|
_force_windows(monkeypatch)
|
|
pkg = tmp_path / "onnxruntime"
|
|
capi = pkg / "capi"
|
|
capi.mkdir(parents=True)
|
|
dll = capi / "onnxruntime.dll"
|
|
dll.write_bytes(b"not really a dll")
|
|
_fake_spec_for(monkeypatch, pkg)
|
|
|
|
assert _ort.ensure_ort_dylib_pinned() == str(dll)
|
|
assert _ort.os.environ["ORT_DYLIB_PATH"] == str(dll)
|
|
|
|
|
|
def test_idempotent_after_first_resolution(monkeypatch, tmp_path):
|
|
_force_windows(monkeypatch)
|
|
pkg = tmp_path / "onnxruntime"
|
|
(pkg / "capi").mkdir(parents=True)
|
|
(pkg / "capi" / "onnxruntime.dll").write_bytes(b"x")
|
|
_fake_spec_for(monkeypatch, pkg)
|
|
|
|
first = _ort.ensure_ort_dylib_pinned()
|
|
# Resolution must not re-run: break find_spec and call again.
|
|
monkeypatch.setattr(
|
|
_ort.importlib.util,
|
|
"find_spec",
|
|
lambda name: pytest.fail("resolution ran twice"),
|
|
)
|
|
assert _ort.ensure_ort_dylib_pinned() == first
|
|
|
|
|
|
def test_no_pin_when_package_missing(monkeypatch):
|
|
_force_windows(monkeypatch)
|
|
monkeypatch.setattr(_ort.importlib.util, "find_spec", lambda name: None)
|
|
assert _ort.ensure_ort_dylib_pinned() is None
|
|
assert "ORT_DYLIB_PATH" not in _ort.os.environ
|
|
|
|
|
|
def test_no_pin_when_native_library_absent(monkeypatch, tmp_path):
|
|
_force_windows(monkeypatch)
|
|
pkg = tmp_path / "onnxruntime"
|
|
pkg.mkdir() # package exists, but no capi/onnxruntime.dll inside
|
|
_fake_spec_for(monkeypatch, pkg)
|
|
assert _ort.ensure_ort_dylib_pinned() is None
|
|
assert "ORT_DYLIB_PATH" not in _ort.os.environ
|
|
|
|
|
|
def test_never_raises(monkeypatch):
|
|
_force_windows(monkeypatch)
|
|
|
|
def boom(name):
|
|
raise RuntimeError("synthetic find_spec failure")
|
|
|
|
monkeypatch.setattr(_ort.importlib.util, "find_spec", boom)
|
|
assert _ort.ensure_ort_dylib_pinned() is None
|
|
assert "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}
|