Skip to content

Commit fd90cd0

Browse files
committed
Warn instead of raising on instrumentation ownership conflicts
init(dsn=...) now reuses the default client when the DSN points to the same project. A second client enabling integrations while another live client owns them logs a warning and leaves automatic tracking with the owner, as 0.2.2 did silently. wildedge run --strict-integrations keeps the RuntimeError.
1 parent 0e24083 commit fd90cd0

10 files changed

Lines changed: 211 additions & 32 deletions

File tree

‎CHANGELOG.md‎

Lines changed: 7 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -41,12 +41,13 @@ under Unreleased and move into a version section at release time.
4141
chat messages and replies. `attachments_enabled=True` enables uploads only for
4242
attachments explicitly passed to `track_inference(attachments=[...])`.
4343
Apps relying on automatic GGUF capture must supply attachments explicitly.
44-
- Enabling an integration or hub on a second live client now raises
45-
`RuntimeError` while another client owns process-wide instrumentation. This
46-
includes `wildedge.init(dsn=..., integrations=[...])` under `wildedge run`.
47-
Previously the second client's patches were skipped without a warning and
48-
automatic events kept going to the first client. Call `init()` without `dsn`
49-
to reuse the client `wildedge run` installed, or close the owner first.
44+
- `wildedge.init(dsn=...)` reuses the existing default client when the DSN
45+
points to the same project, for example `dsn=os.environ["WILDEDGE_DSN"]`
46+
under `wildedge run`. It used to create a second client.
47+
- Enabling an integration or hub on a second client while another live client
48+
owns process-wide instrumentation now logs a warning. Automatic events keep
49+
going to the owner's project, as before, but this used to happen without a
50+
word. With `wildedge run --strict-integrations` it raises `RuntimeError`.
5051
- Quantization labels are defined once in `wildedge.quantizations` and used
5152
by every integration. Behaviour changes:
5253
- MLX-LM reports N-bit weights as `int4`/`int8`, like Transformers, instead

‎docs/deployment.md‎

Lines changed: 12 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -16,8 +16,9 @@ There are three ways a process gets its client, in order of coverage:
1616

1717
All three produce the same thing: one process-wide default client that
1818
`wildedge.span()`, `wildedge.register_model()` and the rest delegate to.
19-
`init()` without `dsn` reuses whatever client already exists, so code written
20-
for in-process init runs unchanged under `wildedge run`.
19+
`init()` without `dsn`, or with the DSN that client already uses, reuses
20+
whatever client already exists, so code written for in-process init runs
21+
unchanged under `wildedge run`.
2122

2223
The lazy mode configures itself from the environment: `WILDEDGE_DSN`,
2324
`WILDEDGE_INTEGRATIONS`, `WILDEDGE_HUBS`. Unset integration variables mean
@@ -99,12 +100,15 @@ them unwrapped or unset `WILDEDGE_DSN` there.
99100
## One client per process
100101

101102
- Framework patches are installed at most once per process. One live client
102-
owns process-wide auto-instrumentation; another client attempting to enable
103-
it raises `RuntimeError` until that owner is closed. Manual tracking does not
104-
claim ownership.
105-
- `init()` reuses the live default client unless you pass `dsn`
106-
explicitly, so the CLI-installed client and application code share one
107-
client instead of racing.
103+
owns process-wide auto-instrumentation. When another client enables an
104+
integration or hub while that owner is live, it logs a warning and
105+
automatic events keep going to the owner's project. The new client still
106+
sends its manual tracking. With `wildedge run --strict-integrations`, the
107+
conflict raises `RuntimeError` instead. Manual tracking does not claim
108+
ownership.
109+
- `init()` reuses the live default client unless you pass a `dsn` for a
110+
different project, so the CLI-installed client and application code share
111+
one client instead of racing.
108112
- Trace and span correlation lives in contextvars at module level, not on a
109113
client. Auto-instrumented events emitted inside `wildedge.trace(...)` /
110114
`wildedge.span(...)` blocks correlate into the same trace no matter which

‎docs/manual-tracking.md‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -26,8 +26,8 @@ with wildedge.trace(run_id="run-123"):
2626
The default client comes from wherever initialization happened first:
2727

2828
- `wildedge run` installs one before your code loads. A later
29-
`wildedge.init()` without `dsn` reuses it, so the same code works with or
30-
without the CLI wrapper.
29+
`wildedge.init()` without `dsn`, or with the same DSN, reuses it, so the
30+
same code works with or without the CLI wrapper.
3131
- `wildedge.init(...)` creates one (or reuses the existing default) and
3232
registers it.
3333
- Any module-level call (`wildedge.span`, `wildedge.register_model`, ...)

‎tests/conftest.py‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -131,4 +131,5 @@ def client_with_stubbed_runtime():
131131
def isolate_instrumentation_owner(monkeypatch):
132132
monkeypatch.setattr(instrumentation, "_owner", None)
133133
monkeypatch.setattr(instrumentation, "_enabled", set())
134+
monkeypatch.setattr(instrumentation, "_strict_ownership", False)
134135
monkeypatch.setattr(huggingface, "_client_route", None)

‎tests/test_cli.py‎

Lines changed: 31 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@
66

77
import pytest
88

9-
from wildedge import cli, constants
9+
from wildedge import cli, constants, instrumentation
1010
from wildedge.defaults import peek_default_client
1111
from wildedge.integrations.registry import IntegrationSpec
1212
from wildedge.platforms.device_info import DeviceInfo
@@ -237,6 +237,36 @@ def instrument(self, name): # type: ignore[no-untyped-def]
237237
bootstrap.install_runtime()
238238

239239

240+
@pytest.mark.parametrize("strict", ["0", "1"])
241+
def test_install_runtime_records_strict_ownership(monkeypatch, strict):
242+
class FakeWildEdge:
243+
SUPPORTED_INTEGRATIONS = {"onnx"}
244+
245+
def __init__(self, *, dsn, app_version, debug, sampling_interval_s=None): # type: ignore[no-untyped-def]
246+
pass
247+
248+
def instrument(self, name): # type: ignore[no-untyped-def]
249+
pass
250+
251+
def flush(self, timeout): # type: ignore[no-untyped-def]
252+
pass
253+
254+
def close(self): # type: ignore[no-untyped-def]
255+
pass
256+
257+
monkeypatch.setattr(bootstrap, "WildEdge", FakeWildEdge)
258+
monkeypatch.setenv(constants.ENV_DSN, "https://secret@ingest.wildedge.dev/key")
259+
monkeypatch.setenv(constants.ENV_INTEGRATIONS, "onnx")
260+
monkeypatch.setenv(constants.ENV_STRICT_INTEGRATIONS, strict)
261+
monkeypatch.setattr(bootstrap.importlib.util, "find_spec", lambda _: object())
262+
263+
context = bootstrap.install_runtime()
264+
try:
265+
assert instrumentation.strict_ownership() is (strict == "1")
266+
finally:
267+
context.shutdown()
268+
269+
240270
def test_doctor_reports_missing_dsn_and_unknown_integration(monkeypatch, capsys):
241271
monkeypatch.delenv("WILDEDGE_DSN", raising=False)
242272
rc = cli.main(["doctor", "--integrations", "madeup"])

‎tests/test_instrumentation_ownership.py‎

Lines changed: 68 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -140,9 +140,32 @@ def test_close_is_idempotent(clients):
140140
client.consumer.close.assert_called_once()
141141

142142

143-
def test_init_conflict_cleans_up_new_client_without_stopping_owner_sampler(
143+
def test_init_with_other_dsn_warns_and_leaves_tracking_with_owner(
144+
clients, monkeypatch, caplog
145+
):
146+
caplog.set_level("WARNING", logger="wildedge")
147+
first = clients()
148+
route = claim_instrumentation(first, "onnx")
149+
set_default_client(first)
150+
second = clients()
151+
monkeypatch.setattr(convenience, "WildEdge", lambda **kwargs: second)
152+
with patch("wildedge.client.stop_sampler") as stop:
153+
result = wildedge.init(
154+
dsn="https://other@localhost/other", integrations=["onnx"]
155+
)
156+
stop.assert_not_called()
157+
assert result is second
158+
assert not second.closed
159+
assert not first.closed
160+
assert route() is first
161+
assert convenience.peek_default_client() is second
162+
assert [r for r in caplog.records if "already owns automatic tracking" in r.message]
163+
164+
165+
def test_strict_ownership_conflict_raises_and_cleans_up_new_client(
144166
clients, monkeypatch
145167
):
168+
instrumentation.set_strict_ownership(True)
146169
first = clients()
147170
claim_instrumentation(first, "onnx")
148171
set_default_client(first)
@@ -157,6 +180,50 @@ def test_init_conflict_cleans_up_new_client_without_stopping_owner_sampler(
157180
assert convenience.peek_default_client() is first
158181

159182

183+
def test_init_with_owner_dsn_reuses_owner(clients, monkeypatch, caplog):
184+
caplog.set_level("WARNING", logger="wildedge")
185+
first = clients()
186+
first.instrument("onnx")
187+
set_default_client(first)
188+
monkeypatch.setattr(
189+
convenience, "WildEdge", MagicMock(side_effect=AssertionError("new client"))
190+
)
191+
assert (
192+
wildedge.init(dsn="https://test@localhost/test", integrations=["onnx"]) is first
193+
)
194+
assert not [r for r in caplog.records if "ignoring" in r.message]
195+
196+
197+
def test_init_with_dsn_none_reuses_owner_of_env_dsn(clients, monkeypatch):
198+
first = clients()
199+
set_default_client(first)
200+
monkeypatch.setenv("WILDEDGE_DSN", "https://test@localhost/test")
201+
monkeypatch.setattr(
202+
convenience, "WildEdge", MagicMock(side_effect=AssertionError("new client"))
203+
)
204+
assert wildedge.init(dsn=None) is first
205+
206+
207+
def test_hub_conflict_warns_and_skips(clients, monkeypatch, caplog):
208+
caplog.set_level("WARNING", logger="wildedge")
209+
installs = []
210+
211+
class Tracker:
212+
def can_install(self):
213+
return True
214+
215+
def install_patch(self, route):
216+
installs.append(route)
217+
218+
monkeypatch.setitem(WildEdge.HUB_TRACKER_CLASSES, "huggingface", Tracker)
219+
first, second = clients(), clients()
220+
first.instrument(None, hubs=["huggingface"])
221+
second.instrument(None, hubs=["huggingface"])
222+
assert len(installs) == 1
223+
assert "huggingface" not in second.hub_trackers
224+
assert [r for r in caplog.records if "already owns automatic tracking" in r.message]
225+
226+
160227
@pytest.mark.parametrize("hub", ["huggingface", "torchhub"])
161228
def test_hub_factory_route_follows_replacement(clients, monkeypatch, hub):
162229
routes = []

‎wildedge/client.py‎

Lines changed: 35 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -23,7 +23,13 @@
2323
from wildedge.events.span import SpanKind, SpanStatus
2424
from wildedge.hubs.base import BaseHubTracker
2525
from wildedge.hubs.registry import HUB_SPECS, supported_hubs
26-
from wildedge.instrumentation import claim_instrumentation, has_other_live_owner
26+
from wildedge.instrumentation import (
27+
ClientRoute,
28+
InstrumentationOwnedError,
29+
claim_instrumentation,
30+
has_other_live_owner,
31+
strict_ownership,
32+
)
2733
from wildedge.integrations.base import BaseExtractor
2834
from wildedge.integrations.registry import (
2935
INTEGRATION_SPECS,
@@ -280,10 +286,14 @@ def __init__(
280286
dsn = env.dsn
281287
debug = env.debug
282288
self.noop = False
289+
# (secret, host, project_key), so init(dsn=...) can tell when a
290+
# requested destination matches this client. None for a no-op client.
291+
self.destination: tuple[str, str, str] | None = None
283292
if not dsn:
284293
self._init_noop(debug=debug, device=device)
285294
return
286295
api_key, host, project_key = parse_dsn(dsn)
296+
self.destination = (api_key, host, project_key)
287297
app_identity = resolve_app_identity(
288298
explicit=env.app_identity,
289299
project_key=project_key,
@@ -689,11 +699,31 @@ def _activate_hub(self, hub_name: str) -> None:
689699
"wildedge: hub '%s' library not installed; skipping", hub_name
690700
)
691701
return
692-
tracker.install_patch(claim_instrumentation(self, "hub:" + hub_name))
702+
route = self._claim_instrumentation("hub:" + hub_name)
703+
if route is None:
704+
return
705+
tracker.install_patch(route)
693706
self.hub_trackers[hub_name] = tracker
694707
if self.debug:
695708
logger.debug("wildedge: hub tracker '%s' activated", hub_name)
696709

710+
def _claim_instrumentation(self, name: str) -> ClientRoute | None:
711+
"""Claim process-wide instrumentation, or warn and skip if owned."""
712+
try:
713+
return claim_instrumentation(self, name)
714+
except InstrumentationOwnedError:
715+
if strict_ownership():
716+
raise
717+
logger.warning(
718+
"wildedge: another WildEdge client (for example the one "
719+
"`wildedge run` installed) already owns automatic tracking, so "
720+
"'%s' events keep going to that client's project. Call "
721+
"wildedge.init() without dsn to reuse that client, or close it "
722+
"before enabling integrations on this one.",
723+
name,
724+
)
725+
return None
726+
697727
def _snapshot_hub_caches(self) -> dict[str, dict[str, int]]:
698728
"""Return a before-snapshot of all active hub cache directories."""
699729
return {
@@ -846,7 +876,9 @@ def instrument(
846876
logger.debug(LOG_INSTRUMENT_TORCH_KERAS, integration)
847877
else:
848878
installer = self.PATCH_INSTALLERS[integration]
849-
installer(claim_instrumentation(self, integration))
879+
route = self._claim_instrumentation(integration)
880+
if route is not None:
881+
installer(route)
850882
for hub_name in hubs or []:
851883
self._activate_hub(hub_name)
852884

‎wildedge/convenience.py‎

Lines changed: 34 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -3,9 +3,10 @@
33
from collections.abc import Iterable
44
from typing import Any
55

6-
from wildedge.client import WildEdge
6+
from wildedge.client import WildEdge, parse_dsn
77
from wildedge.defaults import peek_default_client, set_default_client
88
from wildedge.logging import logger
9+
from wildedge.settings import read_client_env
910

1011

1112
def _normalize_list(value: str | Iterable[str] | None) -> list[str]:
@@ -16,6 +17,20 @@ def _normalize_list(value: str | Iterable[str] | None) -> list[str]:
1617
return [item for item in value if item]
1718

1819

20+
def _same_destination(client: WildEdge, dsn: str | None) -> bool:
21+
"""True when ``dsn`` (or WILDEDGE_DSN) points where ``client`` sends."""
22+
destination = getattr(client, "destination", None)
23+
if destination is None:
24+
return False
25+
resolved = read_client_env(dsn=dsn).dsn
26+
if not resolved:
27+
return False
28+
try:
29+
return parse_dsn(resolved) == destination
30+
except ValueError:
31+
return False
32+
33+
1934
def init(
2035
*,
2136
integrations: str | Iterable[str] | None = None,
@@ -26,23 +41,32 @@ def init(
2641
Initialize the process default client and instrument integrations.
2742
2843
When a live default client already exists (typically installed by ``wildedge
29-
run`` before user code loaded) and no ``dsn`` is passed, that client is
30-
reused: the requested integrations are applied to it (instrumenting is
31-
idempotent per process) and it is returned. Passing ``dsn`` always
32-
constructs a fresh client and makes it the new default after instrumentation
33-
succeeds. A closed default is replaced. Another live instrumentation owner
34-
must be closed before enabling process-wide patches on a new client.
44+
run`` before user code loaded) and no ``dsn`` is passed, or ``dsn`` points
45+
to the same project, that client is reused: the requested integrations are
46+
applied to it (instrumenting is idempotent per process) and it is returned.
47+
A ``dsn`` for another project constructs a fresh client and makes it the new
48+
default. A closed default is replaced. While another live client owns
49+
process-wide instrumentation, the new client logs a warning and leaves
50+
automatic tracking with that owner. With ``wildedge run
51+
--strict-integrations`` it raises ``RuntimeError`` instead.
3552
3653
Additional keyword arguments are forwarded to WildEdge(...) when a new
3754
client is constructed.
3855
"""
39-
client = None if "dsn" in kwargs else peek_default_client()
56+
client = peek_default_client()
4057
if client is not None and client.closed:
4158
client = None
42-
if client is not None and kwargs:
59+
if (
60+
client is not None
61+
and "dsn" in kwargs
62+
and not _same_destination(client, kwargs["dsn"])
63+
):
64+
client = None
65+
ignored = sorted(key for key in kwargs if key != "dsn")
66+
if client is not None and ignored:
4367
logger.warning(
4468
"wildedge: init() reusing the existing default client; ignoring %s",
45-
", ".join(sorted(kwargs)),
69+
", ".join(ignored),
4670
)
4771
created = client is None
4872
if created:

‎wildedge/instrumentation.py‎

Lines changed: 16 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,21 @@
1515
_lock = threading.Lock()
1616
_owner: weakref.ReferenceType[WildEdge] | None = None
1717
_enabled: set[str] = set()
18+
_strict_ownership = False
19+
20+
21+
class InstrumentationOwnedError(RuntimeError):
22+
"""Another live client already owns process-wide instrumentation."""
23+
24+
25+
def set_strict_ownership(strict: bool) -> None:
26+
"""Raise on ownership conflicts instead of warning (`--strict-integrations`)."""
27+
global _strict_ownership
28+
_strict_ownership = strict
29+
30+
31+
def strict_ownership() -> bool:
32+
return _strict_ownership
1833

1934

2035
class ClientRoute:
@@ -67,7 +82,7 @@ def claim_instrumentation(client: WildEdge, integration: str) -> ClientRoute:
6782
raise RuntimeError("Cannot instrument with a closed WildEdge client")
6883
owner = _owner() if _owner is not None else None
6984
if owner is not None and not owner.closed and owner is not client:
70-
raise RuntimeError(
85+
raise InstrumentationOwnedError(
7186
"Auto-instrumentation is owned by another live WildEdge client; "
7287
"close that client before enabling instrumentation on its replacement"
7388
)

0 commit comments

Comments
 (0)