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.

Pin ORT dylib on Windows; init Python logging (#1010)

Parideboy3ccdad6c6733
diff --git a/Cargo.lock b/Cargo.lock
index abcac5c9c..3f54c9a61 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -1961,6 +1961,7 @@ dependencies = [
"cc",
"headroom-core",
"pyo3",
+ "pyo3-log",
"serde_json",
]
@@ -3288,6 +3289,17 @@ dependencies = [
"pyo3-build-config",
]
+[[package]]
+name = "pyo3-log"
+version = "0.12.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "45192e5e4a4d2505587e27806c7b710c231c40c56f3bfc19535d0bb25df52264"
+dependencies = [
+ "arc-swap",
+ "log",
+ "pyo3",
+]
+
[[package]]
name = "pyo3-macros"
version = "0.24.2"
diff --git a/Cargo.toml b/Cargo.toml
index dbb26a7f6..b95cf5d64 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -48,7 +48,11 @@ serde = { version = "1", features = ["derive"] }
serde_json = { version = "1", features = ["preserve_order", "arbitrary_precision", "raw_value"] }
bytes = "1"
thiserror = "1"
-tracing = "0.1"
+# `log` compat: when no tracing subscriber is active (the case inside the
+# headroom-py cdylib), events are re-emitted as `log` records so pyo3-log
+# can forward them to Python's logging. No effect on binaries that install
+# a real subscriber.
+tracing = { version = "0.1", features = ["log"] }
anyhow = "1"
clap = { version = "4", features = ["derive"] }
tokio = { version = "1", features = ["macros", "rt-multi-thread", "signal"] }
@@ -56,6 +60,9 @@ axum = "0.7"
tower = "0.5"
reqwest = { version = "0.12", default-features = false, features = ["json", "rustls-tls"] }
pyo3 = { version = "0.24", features = ["abi3-py310"] }
+# Forwards Rust `log` records (incl. tracing events via the `log` compat
+# feature above) into Python's `logging` inside the _core extension module.
+pyo3-log = "0.12"
# Phase D PR-D1: AWS SigV4 signing for native Bedrock InvokeModel route.
# `aws-sigv4` provides the canonical-request + signing-key implementation;
# `aws-config` resolves credentials from the standard provider chain
diff --git a/crates/headroom-core/src/transforms/magika_detector.rs b/crates/headroom-core/src/transforms/magika_detector.rs
index 8bd9c5a42..7e0cea970 100644
--- a/crates/headroom-core/src/transforms/magika_detector.rs
+++ b/crates/headroom-core/src/transforms/magika_detector.rs
@@ -35,6 +35,7 @@ use std::time::Duration;
use magika::Session;
use thiserror::Error;
+use tracing;
use crate::transforms::content_detector::ContentType;
@@ -75,15 +76,19 @@ static MAGIKA_SESSION: OnceLock<Mutex<Result<Session, String>>> = OnceLock::new(
/// Default cap on magika ONNX session init.
///
/// On some platforms `Session::new()` can hang indefinitely instead of
-/// returning an error. Observed on Windows, where magika's transitive
-/// `ort` takes a DirectML / binary path on first init (fastembed is
-/// Windows-gated to `ort-load-dynamic` in `Cargo.toml` for the same
-/// reason, but magika carries its own `ort`). A hang — unlike an `Err` —
-/// is not caught by the tiered fallback in [`crate::transforms::detection`],
-/// so it stalls the entire compression pipeline until the proxy's own
-/// 30s+ timeout fires on every request. Bounding init converts that hang
-/// into the already-handled `Err` path. Override with
-/// `HEADROOM_MAGIKA_INIT_TIMEOUT_SECS`.
+/// returning an error. Root-caused on Windows: with `ort-load-dynamic`
+/// (Windows-gated in `Cargo.toml`), the bare `LoadLibrary("onnxruntime.dll")`
+/// search resolves to `C:\Windows\System32\onnxruntime.dll` — the Windows ML
+/// OS component (1.17.x on Win11 24H2+) — and initializing an ort 2.x
+/// session against it deadlocks at 0% CPU rather than erroring. A hang —
+/// unlike an `Err` — is not caught by the tiered fallback in
+/// [`crate::transforms::detection`], so it stalls the entire compression
+/// pipeline until the proxy's own 30s+ timeout fires on every request.
+///
+/// The real fix is `headroom/_ort.py`, which pins `ORT_DYLIB_PATH` to the
+/// pip-installed `onnxruntime` DLL before this crate can load ort. This
+/// timeout remains as the safety net for unpinned embedders of the crate.
+/// Override with `HEADROOM_MAGIKA_INIT_TIMEOUT_SECS`.
const MAGIKA_INIT_TIMEOUT_SECS_DEFAULT: u64 = 5;
fn magika_init_timeout() -> Duration {
@@ -112,15 +117,27 @@ fn session() -> &'static Mutex<Result<Session, String>> {
let _ = tx.send(Session::new().map_err(|e| e.to_string()));
});
if let Err(e) = spawned {
+ tracing::warn!("magika init thread spawn failed: {e}");
return Mutex::new(Err(format!("magika init thread spawn failed: {e}")));
}
match rx.recv_timeout(timeout) {
Ok(res) => Mutex::new(res),
- Err(_) => Mutex::new(Err(format!(
- "magika session init exceeded {}s timeout; \
- using non-ML detection tiers",
- timeout.as_secs()
- ))),
+ Err(_) => {
+ let ort_dylib = std::env::var("ORT_DYLIB_PATH").ok();
+ tracing::warn!(
+ timeout_secs = timeout.as_secs(),
+ ort_dylib_path = ort_dylib.as_deref(),
+ "magika ONNX session init timed out; detection falls back to \
+ non-ML tiers for this process. On Windows an unset \
+ ORT_DYLIB_PATH usually means the WinML System32 \
+ onnxruntime.dll was picked up (deadlocks ort init)."
+ );
+ Mutex::new(Err(format!(
+ "magika session init exceeded {}s timeout; \
+ using non-ML detection tiers",
+ timeout.as_secs()
+ )))
+ }
}
})
}
diff --git a/crates/headroom-py/Cargo.toml b/crates/headroom-py/Cargo.toml
index d23eeb7c8..779eef6a4 100644
--- a/crates/headroom-py/Cargo.toml
+++ b/crates/headroom-py/Cargo.toml
@@ -34,4 +34,5 @@ extension-module = ["pyo3/extension-module"]
[dependencies]
headroom-core = { path = "../headroom-core" }
pyo3 = { workspace = true }
+pyo3-log = { workspace = true }
serde_json = { workspace = true }
diff --git a/crates/headroom-py/src/lib.rs b/crates/headroom-py/src/lib.rs
index 249356d86..ae9341c0c 100644
--- a/crates/headroom-py/src/lib.rs
+++ b/crates/headroom-py/src/lib.rs
@@ -1624,6 +1624,17 @@ fn compress_openai_responses_live_zone(
#[pymodule]
fn _core(m: &Bound<'_, PyModule>) -> PyResult<()> {
+ // Bridge Rust diagnostics into Python's `logging`. headroom-core emits
+ // `tracing` events (e.g. magika init timeout warnings), but a cdylib has
+ // no tracing subscriber, so they were silently dropped. The workspace
+ // `tracing` dep now enables the `log` compat feature — events become
+ // `log` records when no subscriber is active — and pyo3-log forwards
+ // those to Python loggers (named like
+ // `headroom_core.transforms.magika_detector`), which is what lands in
+ // the proxy's log file. `try_init` because the global logger may
+ // legitimately already be set (re-import, embedders).
+ let _ = pyo3_log::try_init();
+
m.add_function(wrap_pyfunction!(hello, m)?)?;
m.add_class::<PyDiffCompressorConfig>()?;
m.add_class::<PyDiffCompressionResult>()?;
diff --git a/docs/content/docs/configuration.mdx b/docs/content/docs/configuration.mdx
index 25a01f7fe..bda79f5c9 100644
--- a/docs/content/docs/configuration.mdx
+++ b/docs/content/docs/configuration.mdx
@@ -242,6 +242,8 @@ headroom proxy --learn --min-evidence 3
| `HEADROOM_STRIP_INTERNAL_HEADERS` | Python proxy: whether to strip internal `x-headroom-*` request headers (e.g. `x-headroom-bypass`, `x-headroom-mode`, `x-headroom-user-id`, `x-headroom-stack`, `x-headroom-base-url`) before every upstream forwarder call (PR-A5, fixes P5-49). `enabled` (default) stops fingerprinting / leakage. `disabled` is an explicit operator opt-in for diagnostic shadow tracing — NOT a fallback. Inbound reads of these headers (bypass gating, memory user-id resolution) are unaffected because they read `request.headers` directly. | `enabled` |
| `HEADROOM_PROXY_STRIP_INTERNAL_HEADERS` | Rust proxy: same policy as `HEADROOM_STRIP_INTERNAL_HEADERS` but for the Rust transparent proxy. Stripping happens inside `build_forward_request_headers` so both HTTP and WebSocket upstream calls are gated by one flag. `enabled` default; `disabled` operator opt-in for diagnostic shadow tracing. Response-side `X-Headroom-*` injection (e.g. `x-headroom-tokens-saved`) is unrelated and stays. | `enabled` |
| `HEADROOM_EMBEDDER_RUNTIME` | Set to `pytorch_mps` to run the memory embedder via the torch sentence-transformers backend on the Apple GPU (MPS). Only engages when Apple MPS is actually available; otherwise it logs a warning and uses the existing default embedder selection path. `pytorch_mps` is the only accepted value. Requires the `[pytorch-mps]` extra. See [Memory](/docs/memory#embedding-runtime--gpu-offload-apple-silicon). | default embedder selection |
+| `ORT_DYLIB_PATH` | Windows: path to the `onnxruntime.dll` loaded by the Rust core (magika detection, fastembed embeddings). Auto-pinned at `import headroom` to the DLL inside the `onnxruntime` pip package; set it yourself to override. Without a pin the bare Windows DLL search resolves to the Windows ML System32 build (1.17.x on Win11 24H2+), which deadlocks ONNX session init — see [Troubleshooting](/docs/troubleshooting#windows-ml-content-detection-hangs-or-silently-falls-back). | auto-pinned on Windows |
+| `HEADROOM_MAGIKA_INIT_TIMEOUT_SECS` | Upper bound (integer seconds, > 0) on magika's one-time ONNX session init in the Rust detection chain. On timeout the init error is cached and detection uses the non-ML fallback tiers for the rest of the process; a warning is logged. Safety net for environments where the dylib pin above does not apply. | `5` |
| `HEADROOM_REQUEST_TIMEOUT` | Request timeout in seconds | `300` |
| `HEADROOM_BETA_HEADER_STICKY` | Controls per-session `anthropic-beta` / `OpenAI-Beta` re-echo. `enabled` (default): the proxy unions beta tokens across turns within a session — if the client sends a token in turn N and omits it in turn N+1, the proxy re-injects it to preserve prefix-cache stability. `disabled`: the client's value is forwarded verbatim with no accumulation. Any other value raises at request time. See [Session Beta Header Tracking](/docs/configuration#session-beta-header-tracking). | `enabled` |
| `HEADROOM_BETA_TRACKER_MAX_SESSIONS` | LRU capacity of the in-memory session beta tracker. Once full, the oldest session entry is evicted. | `1000` |
diff --git a/docs/content/docs/troubleshooting.mdx b/docs/content/docs/troubleshooting.mdx
index 8a577275f..537d86973 100644
--- a/docs/content/docs/troubleshooting.mdx
+++ b/docs/content/docs/troubleshooting.mdx
@@ -53,6 +53,39 @@ curl https://api.openai.com/v1/models \
-H "Authorization: Bearer $OPENAI_API_KEY"
```
+### Windows: ML content detection hangs or silently falls back
+
+**Symptom**: On Windows 11 24H2+, every proxied request stalls (historically
+`Optimization failed: TimeoutError`), or the first detection in each process
+burns ~5 seconds and compression quality drops because detection runs on the
+non-ML fallback tiers. The proxy log may show
+`magika ONNX session init timed out`.
+
+**Cause**: The Rust core loads ONNX Runtime dynamically. Without
+`ORT_DYLIB_PATH`, the bare Windows DLL search resolves `onnxruntime.dll` to
+`C:\Windows\System32\onnxruntime.dll` — the Windows ML OS component (1.17.x),
+which deadlocks ort session initialization instead of returning an error.
+
+**Fix**: Headroom pins `ORT_DYLIB_PATH` automatically at import time to the
+DLL inside the `onnxruntime` pip package (included in `headroom-ai[proxy]`).
+Confirm in the startup log:
+
+```
+Pinned ORT_DYLIB_PATH to bundled ONNX Runtime: ...\onnxruntime\capi\onnxruntime.dll
+```
+
+If the pin is skipped (library install without `onnxruntime`), either install
+it or point the variable at any modern ONNX Runtime yourself:
+
+```powershell
+pip install onnxruntime
+# or
+$env:ORT_DYLIB_PATH = "C:\path\to\onnxruntime.dll"
+```
+
+`HEADROOM_MAGIKA_INIT_TIMEOUT_SECS` (default `5`) bounds the init as a safety
+net; on timeout detection degrades to non-ML tiers for the process lifetime.
+
## No Token Savings
**Symptom**: `stats['session']['tokens_saved_total']` is 0.
diff --git a/headroom/__init__.py b/headroom/__init__.py
index 3f73656ce..8c14ea748 100644
--- a/headroom/__init__.py
+++ b/headroom/__init__.py
@@ -73,8 +73,17 @@ from __future__ import annotations
from importlib import import_module
from typing import Any
+from ._ort import ensure_ort_dylib_pinned
from ._version import __version__ # noqa: F401
-from .compress import CompressConfig, CompressResult, compress, compress_spreadsheet
+
+# 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, which
+# deadlocks ort session init (Win11 24H2+). Windows-gated, idempotent,
+# ~microseconds. See `headroom/_ort.py` for the full story.
+ensure_ort_dylib_pinned()
+
+from .compress import CompressConfig, CompressResult, compress, compress_spreadsheet # noqa: E402
# Keep a real callable bound for the one-function compression API so
# `from headroom import compress` is never shadowed by the submodule object.
diff --git a/headroom/_ort.py b/headroom/_ort.py
new file mode 100644
index 000000000..00a55d83c
--- /dev/null
+++ b/headroom/_ort.py
@@ -0,0 +1,105 @@
+"""Pin the ONNX Runtime dylib for the Rust core on Windows.
+
+Why this module exists
+----------------------
+On Windows, ``headroom._core`` consumers of the ``ort`` crate (magika
+content detection, fastembed embeddings) are built with
+``ort-load-dynamic``: the native ``onnxruntime.dll`` is resolved at
+*runtime*. Unless ``ORT_DYLIB_PATH`` is set, ort falls back to a bare
+``LoadLibrary("onnxruntime.dll")`` and the Windows DLL search order
+applies — and ``C:\\Windows\\System32`` wins.
+
+Windows 11 24H2+ ships ``System32\\onnxruntime.dll`` as part of Windows
+ML (observed: 1.17.2603 "os-germanium"). Initializing an ort 2.x
+session against that OS build does not fail — it deadlocks
+indefinitely at 0% CPU, which the tiered detection fallback cannot
+catch (a hang is not an ``Err``). Reproduced and bracketed with
+``scripts/diag_magika_windows.py``: the identical session inits in
+~400ms when ``ORT_DYLIB_PATH`` points at the ``onnxruntime`` pip
+package's DLL (which ``headroom-ai[proxy]`` already depends on).
+
+The fix: before anything can import ``headroom._core``, resolve the
+pip-installed ``onnxruntime\\capi\\onnxruntime.dll`` and export it via
+``ORT_DYLIB_PATH``. ``headroom/__init__.py`` calls this hook, which
+guarantees ordering for every package-level consumer.
+
+Behavior contract
+-----------------
+- Windows-only; a no-op everywhere else.
+- Respects a pre-set ``ORT_DYLIB_PATH`` (user override wins).
+- Locates the ``onnxruntime`` package via ``find_spec`` WITHOUT
+ importing it (importing would load its native code; this hook must
+ stay ~microseconds and side-effect free).
+- Never raises: import-time failure of an optional accelerator must
+ not break ``import headroom``. Without a pin, detection still
+ degrades gracefully through HEADROOM_MAGIKA_INIT_TIMEOUT_SECS and
+ the non-ML tiers.
+"""
+
+from __future__ import annotations
+
+import importlib.util
+import logging
+import os
+import sys
+from pathlib import Path
+
+logger = logging.getLogger(__name__)
+
+_ENV_VAR = "ORT_DYLIB_PATH"
+
+# Tri-state module cache: unset sentinel / resolved path / None (no pin).
+_UNSET = object()
+_pinned: object = _UNSET
+
+
+def ensure_ort_dylib_pinned() -> str | None:
+ """Export ``ORT_DYLIB_PATH`` for the Rust core's ort runtime (Windows).
+
+ Returns the effective dylib path (pinned now or already present in
+ the environment), or ``None`` when no pin applies (non-Windows, or
+ no ``onnxruntime`` package to point at). Idempotent and exception-free.
+ """
+ global _pinned
+ if _pinned is not _UNSET:
+ return _pinned # type: ignore[return-value]
+ _pinned = _resolve_and_pin()
+ return _pinned # type: ignore[return-value]
+
+
+def _resolve_and_pin() -> str | None:
+ if not sys.platform.startswith("win"):
+ return None
+
+ try:
+ existing = os.environ.get(_ENV_VAR)
+ if existing:
+ logger.debug("%s already set; respecting user override: %s", _ENV_VAR, existing)
+ return existing
+
+ spec = importlib.util.find_spec("onnxruntime")
+ if spec is None or not spec.origin:
+ logger.debug(
+ "onnxruntime package not found; %s left unset. The Rust ML detection "
+ "may pick up the Windows ML System32 onnxruntime.dll, which is known "
+ "to deadlock ort init on Windows 11 24H2+ (it then degrades to non-ML "
+ "tiers via HEADROOM_MAGIKA_INIT_TIMEOUT_SECS). Install onnxruntime or "
+ "set %s explicitly.",
+ _ENV_VAR,
+ _ENV_VAR,
+ )
+ return None
+
+ dll = Path(spec.origin).parent / "capi" / "onnxruntime.dll"
+ if not dll.is_file():
+ logger.debug(
+ "onnxruntime package found but %s is missing; %s left unset", dll, _ENV_VAR
+ )
+ return None
+
+ os.environ[_ENV_VAR] = str(dll)
+ logger.info("Pinned %s to bundled ONNX Runtime: %s", _ENV_VAR, dll)
+ return str(dll)
+ except Exception as exc: # never break `import headroom` over an accelerator pin
+ logger.debug("ort dylib pin skipped: %s: %s", type(exc).__name__, exc)
+ return None
diff --git a/headroom/transforms/content_router.py b/headroom/transforms/content_router.py
index daf70b681..80390efa1 100644
--- a/headroom/transforms/content_router.py
+++ b/headroom/transforms/content_router.py
@@ -1934,6 +1934,25 @@ class ContentRouter(Transform):
logger.debug("Magika pre-load skipped: %s", e)
status["magika"] = "skipped"
+ # Surface which onnxruntime dylib the Rust detection chain will load.
+ # On Windows `headroom._ort` pins ORT_DYLIB_PATH at import time; an
+ # unset value there means the bare DLL search applies, which lands on
+ # the Windows ML System32 build known to deadlock ort session init
+ # (Win11 24H2+, see headroom/_ort.py).
+ if sys.platform.startswith("win"):
+ ort_dylib = os.environ.get("ORT_DYLIB_PATH")
+ if ort_dylib:
+ logger.info("ORT dylib for Rust detection: %s", ort_dylib)
+ status["ort_dylib"] = ort_dylib
+ else:
+ logger.warning(
+ "ORT_DYLIB_PATH is unset: Rust ML detection will use the system "
+ "DLL search, which deadlocks against the Windows ML System32 "
+ "onnxruntime.dll on Windows 11 24H2+. Install the `onnxruntime` "
+ "package or set ORT_DYLIB_PATH."
+ )
+ status["ort_dylib"] = "unset"
+
# 3. CodeAware compressor + common tree-sitter parsers
if self.config.enable_code_aware:
code_compressor = self._get_code_compressor()
diff --git a/tests/test_package_init_lazy.py b/tests/test_package_init_lazy.py
index 07af22fe2..eb341fdb7 100644
--- a/tests/test_package_init_lazy.py
+++ b/tests/test_package_init_lazy.py
@@ -171,3 +171,45 @@ def test_dynamic_detector_import_skips_optional_ml_dependencies(tmp_path: Path)
assert data["spacy_loaded"] is False
assert data["sentence_transformers_loaded"] is False
assert data["torch_loaded"] is False
+
+
+def test_compress_spreadsheet_public_import_survives_ort_pin() -> None:
+ """`from headroom import compress_spreadsheet` stays eagerly exported, and the
+ Windows ORT dylib pin still runs before the `.compress` import.
+
+ The pin (`ensure_ort_dylib_pinned`) was inserted above the eager `.compress`
+ import; restoring `compress_spreadsheet` to that line must not reorder it
+ relative to the pin. The `__dict__` check distinguishes the eager import from
+ the lazy `_LAZY_EXPORTS` fallback, which would also resolve the name.
+ """
+ script = textwrap.dedent(
+ """
+ import json
+
+ import headroom
+ from headroom import compress_spreadsheet
+
+ print(json.dumps({
+ "eager": "compress_spreadsheet" in headroom.__dict__,
+ "callable": callable(compress_spreadsheet),
+ }))
+ """
+ )
+
+ result = subprocess.run(
+ [sys.executable, "-c", script],
+ capture_output=True,
+ text=True,
+ check=True,
+ )
+
+ data = json.loads(result.stdout.strip())
+ assert data["eager"] is True
+ assert data["callable"] is True
+
+ # ORT pin must precede the `.compress` import, which must still list the helper.
+ src = (Path(version_module.__file__).parent / "__init__.py").read_text(encoding="utf-8")
+ pin = src.index("ensure_ort_dylib_pinned()")
+ compress_import = src.index("from .compress import")
+ assert pin < compress_import
+ assert "compress_spreadsheet" in src[compress_import : compress_import + 120]
diff --git a/tests/test_transforms/test_ort_dylib.py b/tests/test_transforms/test_ort_dylib.py
new file mode 100644
index 000000000..8930a07ab
--- /dev/null
+++ b/tests/test_transforms/test_ort_dylib.py
@@ -0,0 +1,107 @@
+"""Tests for headroom._ort — the Windows ORT_DYLIB_PATH auto-pin.
+
+The resolver guards the Rust core against the Windows DLL search picking
+up the Windows ML System32 onnxruntime.dll (deadlocks ort session init on
+Win11 24H2+, see headroom/_ort.py). The platform gate is monkeypatched so
+the full logic runs on any CI OS.
+"""
+
+from __future__ import annotations
+
+import sys
+from types import SimpleNamespace
+
+import pytest
+
+import headroom._ort as _ort
+
+
[email protected](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.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_noop_on_non_windows(monkeypatch):
+ monkeypatch.setattr(sys, "platform", "linux")
+ assert _ort.ensure_ort_dylib_pinned() is None
+ assert "ORT_DYLIB_PATH" not in _ort.os.environ
+
+
+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"
+
+
+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_dll_file_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