Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
40 changes: 37 additions & 3 deletions docs/deployment.md
Original file line number Diff line number Diff line change
Expand Up @@ -82,16 +82,50 @@ 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
client. Auto-instrumented events emitted inside `wildedge.trace(...)` /
`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"
Expand Down
30 changes: 18 additions & 12 deletions tests/compat/conftest.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand All @@ -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",
Expand All @@ -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()
42 changes: 41 additions & 1 deletion tests/compat/test_anthropic_compat.py
Original file line number Diff line number Diff line change
Expand Up @@ -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")

Expand Down Expand Up @@ -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()
22 changes: 21 additions & 1 deletion tests/compat/test_onnx_compat.py
Original file line number Diff line number Diff line change
Expand Up @@ -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):
Expand All @@ -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()
50 changes: 49 additions & 1 deletion tests/compat/test_openai_compat.py
Original file line number Diff line number Diff line change
Expand Up @@ -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")

Expand Down Expand Up @@ -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()
9 changes: 9 additions & 0 deletions tests/conftest.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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)
6 changes: 6 additions & 0 deletions tests/test_init.py
Original file line number Diff line number Diff line change
Expand Up @@ -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))

Expand All @@ -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")

Expand All @@ -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

Expand Down
Loading
Loading