diff --git a/CHANGELOG.md b/CHANGELOG.md index 8748b4c..7dbea81 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,13 @@ under Unreleased and move into a version section at release time. ### Fixed +- Process-wide integrations and hub patches now support sequential SDK client + replacement after the previous owner closes. Reinitialization replaces a closed + default; live ownership conflicts raise explicitly. Existing models/provider + clients retain their original destination and must be recreated. Attempts to + use a closed telemetry destination warn once instead of silently dropping + inference/error events. + - timm models now use the requested architecture/variant name for model identity instead of the Python class name, so models such as resnet18 and resnet50 no longer share telemetry. Manual registration falls back to timm architecture diff --git a/docs/deployment.md b/docs/deployment.md index 713c016..48727fa 100644 --- a/docs/deployment.md +++ b/docs/deployment.md @@ -82,9 +82,11 @@ them unwrapped or unset `WILDEDGE_DSN` there. ## One client per process -- Framework patches are installed at most once per process; the first client - to instrument owns the patch. -- `init()` reuses the existing default client unless you pass `dsn` +- Framework patches are installed at most once per process. One live client + owns process-wide auto-instrumentation; another client attempting to enable + it raises `RuntimeError` until that owner is closed. Manual tracking does not + claim ownership. +- `init()` reuses the live default client unless you pass `dsn` explicitly, so the CLI-installed client and application code share one client instead of racing. - Trace and span correlation lives in contextvars at module level, not on a @@ -92,6 +94,38 @@ them unwrapped or unset `WILDEDGE_DSN` there. `wildedge.span(...)` blocks correlate into the same trace no matter which client emits them. +### Replacing a client + +Sequential replacement is supported. Finish any in-flight work and close the +old SDK client before initializing its replacement. Enable integrations and hubs +explicitly on the replacement: previously enabled integrations do not carry over. +Factory patches resolve the new owner without being installed again. Buffered +HuggingFace download provenance is scoped to its owner session and does not +carry over to another project. + +```python +first = wildedge.init(dsn=dsn, integrations=["onnx"]) +session = ort.InferenceSession("model.onnx") +# Run and finish work with session. +first.close(timeout=10) + +second = wildedge.init(dsn=other_dsn, integrations=["onnx"]) +session = ort.InferenceSession("model.onnx") # create after replacement init +``` + +Existing model objects, provider clients, model handles and in-flight streams +remain bound to the original client; they are not automatically transferred to +another project. Recreate auto-instrumented models/provider clients after +initializing the replacement. Attempts to emit inference/error telemetry through +a closed client are dropped with a one-time warning; application inference can +still run. Simply changing the default client does not change instrumentation +ownership. Repeated `close()` calls are harmless. + +`init()` replaces a closed default even when no explicit `dsn` is supplied, +reading the new client's configuration from the environment. If initialization +fails (including an ownership conflict), a newly created client is closed and +the existing default is preserved. + ## Verifying a deployment `wildedge doctor` answers "will events actually flow from this machine" diff --git a/tests/compat/conftest.py b/tests/compat/conftest.py index 891cbb1..fbc19e7 100644 --- a/tests/compat/conftest.py +++ b/tests/compat/conftest.py @@ -113,7 +113,14 @@ def __init__(self, client: wildedge.WildEdge) -> None: self.events: list[dict] = [] # Handles keep a reference to client.publish, so swap it before any # model is registered. - client.publish = self.events.append # type: ignore[method-assign] + original_publish = client.publish + + def publish(event): + original_publish(event) + if not client.closed: + self.events.append(event) + + client.publish = publish # type: ignore[method-assign] def __getattr__(self, name: str): return getattr(self.client, name) @@ -128,10 +135,8 @@ def one(self, event_type: str) -> dict: return found[0] -@pytest.fixture(scope="session") -def _session_client(): - # One client per process, as in a real app: integration patches are - # process-wide and stay bound to the client that installed them (#74). +def make_compat_client(): + """Construct a recording client without background network services.""" with ( patch( "wildedge.client.detect_device", @@ -146,13 +151,14 @@ def _session_client(): enable_offline_persistence=False, sampling_interval_s=0, ) - wrapped = CompatClient(client) - yield wrapped - client.close() + return CompatClient(client) @pytest.fixture -def compat_client(_session_client): - """The shared client, with the events of earlier tests cleared.""" - _session_client.events.clear() - return _session_client +def compat_client(): + """Fresh clients exercise replacement through already-installed process patches.""" + wrapped = make_compat_client() + try: + yield wrapped + finally: + wrapped.close() diff --git a/tests/compat/test_anthropic_compat.py b/tests/compat/test_anthropic_compat.py index c0be842..fe32033 100644 --- a/tests/compat/test_anthropic_compat.py +++ b/tests/compat/test_anthropic_compat.py @@ -4,7 +4,7 @@ import anthropic import pytest -from conftest import sdk_http_module +from conftest import make_compat_client, sdk_http_module httpx = sdk_http_module("anthropic") @@ -342,3 +342,43 @@ def invoke_sync(): error = compat_client.one("error")["error"] assert error["provider_error_code"] == "overloaded_error" assert not compat_client.of_type("inference") + + +def test_replacement_client_keeps_native_helper_ownership(compat_client): + compat_client.instrument("anthropic") + old = _client(lambda request: httpx.Response(200, json=MESSAGE)) + old.messages.create(model="claude-haiku-4-5", max_tokens=32, messages=[]) + compat_client.close() + replacement = make_compat_client() + try: + replacement.instrument("anthropic") + old.messages.create(model="claude-haiku-4-5", max_tokens=32, messages=[]) + events = [ + { + "type": "message_start", + "message": {**MESSAGE, "content": [], "stop_reason": None}, + }, + { + "type": "message_delta", + "delta": {"stop_reason": "end_turn", "stop_sequence": None}, + "usage": {"output_tokens": 3}, + }, + {"type": "message_stop"}, + ] + body = "".join(f"event: {e['type']}\ndata: {json.dumps(e)}\n\n" for e in events) + with ( + _client( + lambda request: httpx.Response( + 200, text=body, headers={"content-type": "text/event-stream"} + ) + ) as new, + new.messages.stream( + model="claude-haiku-4-5", max_tokens=32, messages=[] + ) as stream, + ): + assert stream.get_final_message().usage.output_tokens == 3 + assert len(compat_client.of_type("inference")) == 1 + replacement.one("inference") + finally: + old.close() + replacement.close() diff --git a/tests/compat/test_onnx_compat.py b/tests/compat/test_onnx_compat.py index 541d7fc..3436ce6 100644 --- a/tests/compat/test_onnx_compat.py +++ b/tests/compat/test_onnx_compat.py @@ -2,7 +2,7 @@ import numpy as np import onnxruntime as ort -from conftest import FIXTURES +from conftest import FIXTURES, make_compat_client def test_inference_session_load_and_run_are_tracked(compat_client): @@ -24,3 +24,23 @@ def test_inference_session_load_and_run_are_tracked(compat_client): inference = compat_client.one("inference") assert inference["model_id"] == "identity" assert inference["inference"]["success"] is True + + +def test_replacement_client_tracks_new_sessions_only(compat_client): + compat_client.instrument("onnx") + path = str(FIXTURES / "identity.onnx") + old = ort.InferenceSession(path, providers=["CPUExecutionProvider"]) + x = np.arange(4, dtype=np.float32).reshape(1, 4) + old.run(None, {"x": x}) + compat_client.close() + replacement = make_compat_client() + try: + replacement.instrument("onnx") + old.run(None, {"x": x}) + new = ort.InferenceSession(path, providers=["CPUExecutionProvider"]) + assert np.array_equal(new.run(None, {"x": x})[0], x) + assert len(compat_client.of_type("inference")) == 1 + replacement.one("model_load") + replacement.one("inference") + finally: + replacement.close() diff --git a/tests/compat/test_openai_compat.py b/tests/compat/test_openai_compat.py index 6e26539..8641959 100644 --- a/tests/compat/test_openai_compat.py +++ b/tests/compat/test_openai_compat.py @@ -6,7 +6,7 @@ import openai import pytest -from conftest import sdk_http_module +from conftest import make_compat_client, sdk_http_module httpx = sdk_http_module("openai") @@ -360,3 +360,51 @@ def handler(request): assert inference["success"] is False assert inference["error_code"] == "STREAM_CLOSED" assert inference["output_meta"]["time_to_first_token_ms"] is not None + + +@pytest.mark.parametrize("asynchronous", [False, True]) +async def test_replacement_client_gets_new_provider_clients( + compat_client, asynchronous +): + compat_client.instrument("openai") + + def handler(request): + return httpx.Response(200, json=COMPLETION) + + if asynchronous: + old = openai.AsyncOpenAI( + api_key="sk-compat", + http_client=httpx.AsyncClient(transport=httpx.MockTransport(handler)), + ) + await old.chat.completions.create(model="gpt-4o-mini", messages=[]) + else: + old = _client(handler) + old.chat.completions.create(model="gpt-4o-mini", messages=[]) + compat_client.one("inference") + compat_client.close() + replacement = make_compat_client() + try: + replacement.instrument("openai") + if asynchronous: + await old.chat.completions.create(model="gpt-4o-mini", messages=[]) + async with openai.AsyncOpenAI( + api_key="sk-compat", + http_client=httpx.AsyncClient(transport=httpx.MockTransport(handler)), + ) as new: + await new.chat.completions.create(model="gpt-4o-mini", messages=[]) + await new.chat.completions.create(model="gpt-4o-mini", messages=[]) + await old.close() + else: + old.chat.completions.create(model="gpt-4o-mini", messages=[]) + with _client(handler) as new: + new.chat.completions.create(model="gpt-4o-mini", messages=[]) + new.chat.completions.create(model="gpt-4o-mini", messages=[]) + old.close() + assert len(compat_client.of_type("inference")) == 1 + assert len(replacement.of_type("inference")) == 2 + assert ( + replacement.registry.handles["gpt-4o-mini"] + is not compat_client.registry.handles["gpt-4o-mini"] + ) + finally: + replacement.close() diff --git a/tests/conftest.py b/tests/conftest.py index 88f2f0a..e9f04ae 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -6,6 +6,8 @@ import pytest +import wildedge.hubs.huggingface as huggingface +import wildedge.instrumentation as instrumentation import wildedge.paths as paths from wildedge.client import WildEdge from wildedge.defaults import set_default_client @@ -123,3 +125,10 @@ def client_with_stubbed_runtime(): dsn="https://secret@ingest.wildedge.dev/key", sampling_interval_s=None, ) + + +@pytest.fixture(autouse=True) +def isolate_instrumentation_owner(monkeypatch): + monkeypatch.setattr(instrumentation, "_owner", None) + monkeypatch.setattr(instrumentation, "_enabled", set()) + monkeypatch.setattr(huggingface, "_client_route", None) diff --git a/tests/test_init.py b/tests/test_init.py index f09e510..37eed7b 100644 --- a/tests/test_init.py +++ b/tests/test_init.py @@ -74,6 +74,8 @@ def test_init_reuses_existing_default_client(monkeypatch): calls: list[tuple[str | None, list[str] | None]] = [] class ExistingClient: + closed = False + def instrument(self, integration, *, hubs=None): calls.append((integration, hubs)) @@ -89,6 +91,8 @@ def instrument(self, integration, *, hubs=None): def test_init_with_dsn_replaces_default_client(monkeypatch): class ExistingClient: + closed = False + def instrument(self, integration, *, hubs=None): raise AssertionError("existing client must not be touched") @@ -112,6 +116,8 @@ def instrument(self, integration, *, hubs=None): def test_init_reuse_warns_about_ignored_kwargs(monkeypatch): class ExistingClient: + closed = False + def instrument(self, integration, *, hubs=None): pass diff --git a/tests/test_instrumentation_ownership.py b/tests/test_instrumentation_ownership.py new file mode 100644 index 0000000..2ac27dc --- /dev/null +++ b/tests/test_instrumentation_ownership.py @@ -0,0 +1,245 @@ +from __future__ import annotations + +import gc +import threading +import weakref +from concurrent.futures import ThreadPoolExecutor +from unittest.mock import MagicMock, patch + +import pytest + +import wildedge +import wildedge.convenience as convenience +import wildedge.hubs.huggingface as huggingface +import wildedge.instrumentation as instrumentation +from wildedge.client import WildEdge +from wildedge.defaults import set_default_client +from wildedge.instrumentation import BoundClientReference, claim_instrumentation +from wildedge.platforms.device_info import DeviceInfo + + +class Owner: + closed = False + + +def test_sequential_replacement_and_opt_in(): + first = Owner() + route = claim_instrumentation(first, "onnx") + assert route() is first + assert claim_instrumentation(first, "onnx")() is first + first.closed = True + assert route() is None + second = Owner() + other = claim_instrumentation(second, "openai") + assert other() is second + assert route() is None + claim_instrumentation(second, "onnx") + assert route() is second + + +def test_live_owner_conflict_does_not_redirect(): + first, second = Owner(), Owner() + route = claim_instrumentation(first, "onnx") + with pytest.raises(RuntimeError, match="another live"): + claim_instrumentation(second, "openai") + assert route() is first + + +def test_dead_owner_can_be_replaced(): + first = Owner() + ref = weakref.ref(first) + route = claim_instrumentation(first, "onnx") + del first + gc.collect() + assert ref() is None + second = Owner() + claim_instrumentation(second, "onnx") + assert route() is second + + +def test_provider_reference_never_follows_replacement(caplog): + caplog.set_level("WARNING", logger="wildedge") + first, second = Owner(), Owner() + claim_instrumentation(first, "openai") + ref = BoundClientReference(first) + first.closed = True + claim_instrumentation(second, "openai") + assert ref() is None + assert ref() is None + assert len([r for r in caplog.records if "recreate" in r.message]) == 1 + + +@pytest.fixture +def clients(): + created = [] + with ( + patch( + "wildedge.client.detect_device", + return_value=DeviceInfo(device_id="replacement-test", device_type="linux"), + ), + patch("wildedge.client.Consumer"), + patch("wildedge.client.Transmitter"), + ): + + def create(): + client = WildEdge( + dsn="https://test@localhost/test", + sampling_interval_s=0, + enable_offline_persistence=False, + ) + created.append(client) + return client + + yield create + for client in created: + client.close() + + +@pytest.mark.parametrize("integration", sorted(WildEdge.PATCH_INSTALLERS)) +def test_shared_route_reuses_first_factory_binding(clients, monkeypatch, integration): + routes = [] + installer = MagicMock( + side_effect=lambda route: routes.append(route) if not routes else None + ) + monkeypatch.setitem(WildEdge.PATCH_INSTALLERS, integration, installer) + first = clients() + first.instrument(integration) + assert routes[0]() is first + first.close() + second = clients() + second.instrument(integration) + assert routes[0]() is second + assert len(routes) == 1 + + +def test_closed_model_handle_does_not_move_projects(clients, caplog): + caplog.set_level("WARNING", logger="wildedge") + first = clients() + handle = first.register_model(object(), model_id="model", auto_instrument=False) + first.close() + second = clients() + handle.track_inference(duration_ms=1) + handle.track_inference(duration_ms=2) + assert first.pending_count() == second.pending_count() == 0 + assert len([r for r in caplog.records if "closed SDK client" in r.message]) == 1 + + +def test_init_replaces_closed_default(clients, monkeypatch): + first = clients() + set_default_client(first) + first.close() + second = clients() + monkeypatch.setattr(convenience, "WildEdge", lambda **kwargs: second) + assert wildedge.init() is second + + +def test_close_is_idempotent(clients): + client = clients() + client.close() + client.close() + client.consumer.close.assert_called_once() + + +def test_init_conflict_cleans_up_new_client_without_stopping_owner_sampler( + clients, monkeypatch +): + first = clients() + claim_instrumentation(first, "onnx") + set_default_client(first) + second = clients() + monkeypatch.setattr(convenience, "WildEdge", lambda **kwargs: second) + with patch("wildedge.client.stop_sampler") as stop: + with pytest.raises(RuntimeError, match="another live"): + wildedge.init(dsn="https://other@localhost/other", integrations=["onnx"]) + stop.assert_not_called() + assert second.closed + assert not first.closed + assert convenience.peek_default_client() is first + + +@pytest.mark.parametrize("hub", ["huggingface", "torchhub"]) +def test_hub_factory_route_follows_replacement(clients, monkeypatch, hub): + routes = [] + + class Tracker: + def can_install(self): + return True + + def install_patch(self, route): + if not routes: + routes.append(route) + + monkeypatch.setitem(WildEdge.HUB_TRACKER_CLASSES, hub, Tracker) + first = clients() + first.instrument(None, hubs=[hub]) + assert routes[0]() is first + first.close() + second = clients() + second.instrument(None, hubs=[hub]) + assert routes[0]() is second + assert first.hub_trackers[hub] is not second.hub_trackers[hub] + + +def test_changing_default_does_not_change_instrumentation_owner(clients): + first, second = clients(), clients() + route = claim_instrumentation(first, "openai") + set_default_client(second) + assert route() is first + + +def test_closed_client_cannot_instrument(clients): + client = clients() + client.close() + with pytest.raises(RuntimeError, match="closed"): + client.instrument("onnx") + + +def test_fork_child_replaces_inherited_lock(): + first = Owner() + route = claim_instrumentation(first, "onnx") + with instrumentation._lock: + instrumentation._reset_lock_after_fork() + assert route() is first + + +def test_concurrent_claims_choose_one_owner(): + owners = [Owner(), Owner()] + barrier = threading.Barrier(2, timeout=2) + + def acquire(owner): + barrier.wait() + try: + return claim_instrumentation(owner, "onnx") + except RuntimeError: + return None + + with ThreadPoolExecutor(max_workers=2) as executor: + results = list(executor.map(acquire, owners)) + routes = [route for route in results if route is not None] + assert len(routes) == 1 + assert routes[0]() in owners + + +def test_hub_provenance_buffer_does_not_cross_owners(clients, monkeypatch): + first = clients() + route = claim_instrumentation(first, "hub:huggingface") + monkeypatch.setattr(huggingface, "_client_route", route) + monkeypatch.setattr(huggingface, "_local", threading.local()) + record = { + "repo_id": "first-project/model", + "size": 1, + "duration_ms": 1, + "cache_hit": True, + "bandwidth_bps": None, + } + huggingface._record_download(**record) + first.close() + second = clients() + claim_instrumentation(second, "onnx") + huggingface._record_download(**record) + claim_instrumentation(second, "hub:huggingface") + assert huggingface.HuggingFaceHubTracker().drain() == [] + huggingface._record_download(**{**record, "repo_id": "second-project/model"}) + assert [r["repo_id"] for r in huggingface.HuggingFaceHubTracker().drain()] == [ + "second-project/model" + ] diff --git a/wildedge/client.py b/wildedge/client.py index d21fded..1a5acb2 100644 --- a/wildedge/client.py +++ b/wildedge/client.py @@ -25,6 +25,7 @@ from wildedge.hubs.huggingface import HuggingFaceHubTracker from wildedge.hubs.registry import supported_hubs from wildedge.hubs.torchhub import TorchHubTracker +from wildedge.instrumentation import claim_instrumentation, has_other_live_owner from wildedge.integrations.anthropic import AnthropicExtractor from wildedge.integrations.base import BaseExtractor from wildedge.integrations.gguf import GgufExtractor @@ -482,6 +483,15 @@ def _init_noop(self, *, debug: bool, device: DeviceInfo | None) -> None: def publish(self, event_dict: dict) -> None: if self.closed or self.noop: + if ( + not self.noop + and event_dict.get("event_type") in ("inference", "error") + and not getattr(self, "_closed_publish_warned", False) + ): + self._closed_publish_warned = True + logger.warning( + "wildedge: event belongs to a closed SDK client; recreate models after initializing its replacement" + ) return if self.debug: @@ -707,7 +717,7 @@ def _activate_hub(self, hub_name: str) -> None: "wildedge: hub '%s' library not installed; skipping", hub_name ) return - tracker.install_patch(weakref.ref(self)) + tracker.install_patch(claim_instrumentation(self, "hub:" + hub_name)) self.hub_trackers[hub_name] = tracker if self.debug: logger.debug("wildedge: hub tracker '%s' activated", hub_name) @@ -814,6 +824,8 @@ def instrument( if self.debug: logger.debug("wildedge: instrument skipped (no DSN configured)") return + if self.closed: + raise RuntimeError("Cannot instrument with a closed WildEdge client") if integration is None: if not hubs: raise ValueError( @@ -859,7 +871,7 @@ def instrument( logger.debug(LOG_INSTRUMENT_TORCH_KERAS, integration) else: installer = self.PATCH_INSTALLERS[integration] - installer(weakref.ref(self)) + installer(claim_instrumentation(self, integration)) for hub_name in hubs or []: self._activate_hub(hub_name) @@ -1008,8 +1020,10 @@ def close(self, timeout: float | None = None) -> None: With a timeout, buffered attachments are uploaded in the time left after the event flush. Without one, they stay on disk for the next start. """ + if self.closed: + return self.closed = True - if not self.noop: + if not self.noop and not has_other_live_owner(self): stop_sampler() if self.attachment_uploader is not None: self.attachment_uploader.stop() diff --git a/wildedge/convenience.py b/wildedge/convenience.py index bfa2f1a..4086d8d 100644 --- a/wildedge/convenience.py +++ b/wildedge/convenience.py @@ -25,34 +25,44 @@ def init( """ Initialize the process default client and instrument integrations. - When a default client already exists (typically installed by ``wildedge + When a live default client already exists (typically installed by ``wildedge run`` before user code loaded) and no ``dsn`` is passed, that client is reused: the requested integrations are applied to it (instrumenting is idempotent per process) and it is returned. Passing ``dsn`` always - constructs a fresh client and makes it the new default. + constructs a fresh client and makes it the new default after instrumentation + succeeds. A closed default is replaced. Another live instrumentation owner + must be closed before enabling process-wide patches on a new client. Additional keyword arguments are forwarded to WildEdge(...) when a new client is constructed. """ client = None if "dsn" in kwargs else peek_default_client() + if client is not None and client.closed: + client = None if client is not None and kwargs: logger.warning( "wildedge: init() reusing the existing default client; ignoring %s", ", ".join(sorted(kwargs)), ) - if client is None: + created = client is None + if created: client = WildEdge(**kwargs) normalized_integrations = _normalize_list(integrations) normalized_hubs = _normalize_list(hubs) - if normalized_integrations: - for integration in normalized_integrations: - client.instrument(integration, hubs=normalized_hubs or None) - elif normalized_hubs: - client.instrument(None, hubs=normalized_hubs) - elif getattr(client, "debug", False): - logger.debug("wildedge: init called without integrations or hubs") + try: + if normalized_integrations: + for integration in normalized_integrations: + client.instrument(integration, hubs=normalized_hubs or None) + elif normalized_hubs: + client.instrument(None, hubs=normalized_hubs) + elif getattr(client, "debug", False): + logger.debug("wildedge: init called without integrations or hubs") + except Exception: + if created: + client.close() + raise set_default_client(client) return client diff --git a/wildedge/hubs/base.py b/wildedge/hubs/base.py index 1e41461..ca2ad73 100644 --- a/wildedge/hubs/base.py +++ b/wildedge/hubs/base.py @@ -45,9 +45,9 @@ def install_patch(self, client_ref: object) -> None: """ Monkey-patch the hub library's download or load functions. - Called at most once per process. ``client_ref`` is a ``weakref.ref`` - to the ``WildEdge`` client; dereference it before use and guard against - ``None`` (client may have been closed or garbage-collected). + Patches are installed at most once per process. ``client_ref`` is a + callable resolving the current enabled owner, or ``None`` when inactive. + Call it before publishing; activation may repeat for a replacement owner. """ @abstractmethod diff --git a/wildedge/hubs/huggingface.py b/wildedge/hubs/huggingface.py index 239ea69..9e72b37 100644 --- a/wildedge/hubs/huggingface.py +++ b/wildedge/hubs/huggingface.py @@ -15,6 +15,7 @@ import time from wildedge.hubs.base import BaseHubTracker +from wildedge.instrumentation import ClientRoute from wildedge.logging import logger from wildedge.timing import elapsed_ms @@ -28,9 +29,16 @@ _local = threading.local() _hf_hub_download_patched = False _snapshot_download_patched = False +_client_route: ClientRoute | None = None def _buffer() -> list[dict]: + if _client_route is not None: + client = _client_route() + session = client.session_id if client is not None else None + if getattr(_local, "owner_session", None) != session: + _local.records = [] + _local.owner_session = session if not hasattr(_local, "records"): _local.records = [] return _local.records @@ -44,7 +52,10 @@ def _record_download( cache_hit: bool, bandwidth_bps: int | None, ) -> None: - _buffer().append( + records = _buffer() + if _client_route is not None and _client_route() is None: + return + records.append( { "repo_id": repo_id, "size": size, @@ -246,12 +257,12 @@ def install_patch(self, client_ref: object) -> None: """ Patch ``hf_hub_download`` and ``snapshot_download`` for thread-local tracking. - ``client_ref`` is accepted for interface consistency but not used: the HF - hub tracker buffers records in a thread-local store and relies on the - client draining them via ``_drain_hub_trackers()`` in - ``_on_model_auto_loaded``. + Thread-local records are scoped to the enabled owner's session so a + replacement cannot drain provenance buffered for a previous project. """ - global _hf_hub_download_patched, _snapshot_download_patched + global _hf_hub_download_patched, _snapshot_download_patched, _client_route + if isinstance(client_ref, ClientRoute): + _client_route = client_ref if _hf_hub_download_patched and _snapshot_download_patched: return diff --git a/wildedge/instrumentation.py b/wildedge/instrumentation.py new file mode 100644 index 0000000..9b988b2 --- /dev/null +++ b/wildedge/instrumentation.py @@ -0,0 +1,93 @@ +"""Ownership of process-wide instrumentation, independent of the default client.""" + +from __future__ import annotations + +import os +import threading +import weakref +from typing import TYPE_CHECKING + +from wildedge.logging import logger + +if TYPE_CHECKING: + from wildedge.client import WildEdge + +_lock = threading.Lock() +_owner: weakref.ReferenceType[WildEdge] | None = None +_enabled: set[str] = set() + + +class ClientRoute: + """Stable callable captured by a factory patch, resolving its current owner.""" + + def __init__(self, integration: str) -> None: + self.integration = integration + + def __call__(self) -> WildEdge | None: + with _lock: + client = _owner() if _owner is not None else None + if client is None or client.closed or self.integration not in _enabled: + return None + return client + + +class BoundClientReference: + """Existing provider clients stay with their original telemetry destination.""" + + def __init__(self, client: WildEdge) -> None: + self._ref = weakref.ref(client) + self._warned = False + + def __call__(self) -> WildEdge | None: + client = self._ref() + if client is None or client.closed: + if not self._warned: + logger.warning( + "wildedge: provider client belongs to an unavailable SDK client; " + "recreate it after initializing the replacement SDK client" + ) + self._warned = True + return None + return client + + +def bind_client_reference(reference: object, client: WildEdge) -> object: + """Snapshot a shared factory route when creating an individual provider client.""" + return ( + BoundClientReference(client) + if isinstance(reference, ClientRoute) + else reference + ) + + +def claim_instrumentation(client: WildEdge, integration: str) -> ClientRoute: + global _owner + with _lock: + if client.closed: + raise RuntimeError("Cannot instrument with a closed WildEdge client") + owner = _owner() if _owner is not None else None + if owner is not None and not owner.closed and owner is not client: + raise RuntimeError( + "Auto-instrumentation is owned by another live WildEdge client; " + "close that client before enabling instrumentation on its replacement" + ) + if owner is not client: + _enabled.clear() + _owner = weakref.ref(client) + _enabled.add(integration) + return ClientRoute(integration) + + +def has_other_live_owner(client: WildEdge) -> bool: + with _lock: + owner = _owner() if _owner is not None else None + return owner is not None and not owner.closed and owner is not client + + +def _reset_lock_after_fork() -> None: + global _lock + _lock = threading.Lock() + + +if hasattr(os, "register_at_fork"): + os.register_at_fork(after_in_child=_reset_lock_after_fork) diff --git a/wildedge/integrations/anthropic.py b/wildedge/integrations/anthropic.py index c0bed75..89682f9 100644 --- a/wildedge/integrations/anthropic.py +++ b/wildedge/integrations/anthropic.py @@ -9,6 +9,7 @@ from typing import TYPE_CHECKING, Any from wildedge.events.inference import ApiMeta, GenerationOutputMeta, TextInputMeta +from wildedge.instrumentation import bind_client_reference from wildedge.integrations.base import BaseExtractor from wildedge.integrations.common import ( AsyncStreamWrapper, @@ -470,8 +471,9 @@ def patched_sync_init(self_inner, *args, **kwargs): # type: ignore[no-untyped-d original_sync_init(self_inner, *args, **kwargs) c = client_ref() # type: ignore[call-arg] if c is not None and not c.closed: + bound_ref = bind_client_reference(client_ref, c) try: - wrap_sync_messages(self_inner.messages, client_ref) + wrap_sync_messages(self_inner.messages, bound_ref) except Exception as exc: debug_anthropic_failure("sync client wrap", exc) @@ -479,8 +481,9 @@ def patched_async_init(self_inner, *args, **kwargs): # type: ignore[no-untyped- original_async_init(self_inner, *args, **kwargs) c = client_ref() # type: ignore[call-arg] if c is not None and not c.closed: + bound_ref = bind_client_reference(client_ref, c) try: - wrap_async_messages(self_inner.messages, client_ref) + wrap_async_messages(self_inner.messages, bound_ref) except Exception as exc: debug_anthropic_failure("async client wrap", exc) diff --git a/wildedge/integrations/openai.py b/wildedge/integrations/openai.py index d295148..a95b97b 100644 --- a/wildedge/integrations/openai.py +++ b/wildedge/integrations/openai.py @@ -14,6 +14,7 @@ GenerationOutputMeta, TextInputMeta, ) +from wildedge.instrumentation import bind_client_reference from wildedge.integrations.base import BaseExtractor from wildedge.integrations.common import ( SOURCE_BY_HOSTNAME, # noqa: F401 (re-exported; moved to common) @@ -597,26 +598,25 @@ def patched_sync_init(self_inner, *args, **kwargs): # type: ignore[no-untyped-d original_sync_init(self_inner, *args, **kwargs) c = client_ref() # type: ignore[call-arg] if c is not None and not c.closed: + bound_ref = bind_client_reference(client_ref, c) source = source_from_base_url( str(getattr(self_inner, "base_url", None) or "") ) try: wrap_sync_completions( - self_inner.chat.completions, source, client_ref + self_inner.chat.completions, source, bound_ref ) except Exception as exc: debug_openai_failure("sync client wrap", exc) if hasattr(self_inner, "responses"): try: - wrap_sync_responses( - self_inner.responses, source, client_ref - ) + wrap_sync_responses(self_inner.responses, source, bound_ref) except Exception as exc: debug_openai_failure("sync responses wrap", exc) if hasattr(self_inner, "embeddings"): try: wrap_sync_embeddings( - self_inner.embeddings, source, client_ref + self_inner.embeddings, source, bound_ref ) except Exception as exc: debug_openai_failure("sync embeddings wrap", exc) @@ -625,26 +625,27 @@ def patched_async_init(self_inner, *args, **kwargs): # type: ignore[no-untyped- original_async_init(self_inner, *args, **kwargs) c = client_ref() # type: ignore[call-arg] if c is not None and not c.closed: + bound_ref = bind_client_reference(client_ref, c) source = source_from_base_url( str(getattr(self_inner, "base_url", None) or "") ) try: wrap_async_completions( - self_inner.chat.completions, source, client_ref + self_inner.chat.completions, source, bound_ref ) except Exception as exc: debug_openai_failure("async client wrap", exc) if hasattr(self_inner, "responses"): try: wrap_async_responses( - self_inner.responses, source, client_ref + self_inner.responses, source, bound_ref ) except Exception as exc: debug_openai_failure("async responses wrap", exc) if hasattr(self_inner, "embeddings"): try: wrap_async_embeddings( - self_inner.embeddings, source, client_ref + self_inner.embeddings, source, bound_ref ) except Exception as exc: debug_openai_failure("async embeddings wrap", exc)