From d7fc6a617816a14979325586e8523ca795dce219 Mon Sep 17 00:00:00 2001 From: Piotr Duda Date: Wed, 21 Oct 2026 19:02:52 +0200 Subject: [PATCH 1/7] Fix whisper example span kind and add uv script header --- examples/whisper_example.py | 17 +++++++++++++---- 1 file changed, 13 insertions(+), 4 deletions(-) diff --git a/examples/whisper_example.py b/examples/whisper_example.py index 7c5a1f2..f00a59d 100644 --- a/examples/whisper_example.py +++ b/examples/whisper_example.py @@ -1,8 +1,17 @@ +# /// script +# requires-python = ">=3.10" +# dependencies = ["wildedge-sdk"] +# +# [tool.uv.sources] +# wildedge-sdk = { path = "..", editable = true } +# /// """Transcribe a WAV using a local Whisper model with automatic instrumentation. -Install mlx-whisper (Apple Silicon) or faster-whisper, set WILDEDGE_DSN, then: - python examples/whisper_example.py mlx_whisper /path/to/model /path/to/audio.wav - python examples/whisper_example.py faster_whisper /path/to/model /path/to/audio.wav +Set WILDEDGE_DSN, then add the backend you want to run: + uv run --with mlx-whisper examples/whisper_example.py mlx_whisper MODEL AUDIO + uv run --with faster-whisper examples/whisper_example.py faster_whisper MODEL AUDIO + +MODEL is a local path or Hugging Face repo, AUDIO is a WAV file. See docs/whisper.md for lifecycle and explicit attachment examples. """ @@ -20,7 +29,7 @@ def main(): args = parser.parse_args() client = wildedge.init(integrations=[args.backend]) try: - with client.trace(), client.span(name="transcribe"): + with client.trace(), client.span(kind="agent_step", name="transcribe"): if args.backend == "mlx_whisper": import mlx_whisper # noqa: PLC0415 -- optional runtime From faa5f77fbb6e117dadc434dd62e803a4ba7e679b Mon Sep 17 00:00:00 2001 From: Piotr Duda Date: Wed, 21 Oct 2026 19:03:33 +0200 Subject: [PATCH 2/7] Pin httpx 0.27 for the openai min compat rows openai 1.30.0 passes proxies= to httpx, which httpx 0.28 removed. --- docs/compatibility.md | 2 +- scripts/compat_matrix.py | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/docs/compatibility.md b/docs/compatibility.md index 0c08065..e5aec96 100644 --- a/docs/compatibility.md +++ b/docs/compatibility.md @@ -59,7 +59,7 @@ To run the full matrix locally: `python scripts/run_compat_local.py`. | `tensorflow` | `current` (`py3.10` override) | `tensorflow==2.21.0`, `keras==3.12.4`, `numpy==2.2.6` | 3.10 | | `llama_cpp` | `min` | `llama-cpp-python==0.2.90`, `numpy==1.26.4` | 3.10, 3.11, 3.12, 3.13 | | `llama_cpp` | `current` | `llama-cpp-python==0.3.36`, `numpy==2.2.6` | 3.10, 3.11, 3.12, 3.13 | -| `openai` | `min` | `openai==1.30.0` | 3.10, 3.11, 3.12, 3.13 | +| `openai` | `min` | `openai==1.30.0`, `httpx==0.27.2` | 3.10, 3.11, 3.12, 3.13 | | `openai` | `current` | `openai==3.35.1` | 3.10, 3.11, 3.12, 3.13 | | `transformers` | `min` | `transformers==4.40.0`, `torch==2.4.1`, `numpy==1.26.4` | 3.10, 3.11, 3.12, 3.13 | | `transformers` | `min` (`py3.13` override) | `transformers==4.45.0`, `torch==2.5.0`, `numpy==2.1.3` | 3.13 | diff --git a/scripts/compat_matrix.py b/scripts/compat_matrix.py index 038ab7b..97f424e 100644 --- a/scripts/compat_matrix.py +++ b/scripts/compat_matrix.py @@ -44,7 +44,7 @@ "current": ["llama-cpp-python==0.3.36", "numpy==2.2.6"], }, "openai": { - "min": ["openai==1.30.0"], + "min": ["openai==1.30.0", "httpx==0.27.2"], "current": ["openai==3.35.1"], }, "transformers": { From f1225f5e99bd1fdb8a5af1d71375b4f4245b064d Mon Sep 17 00:00:00 2001 From: Piotr Duda Date: Wed, 21 Oct 2026 19:04:12 +0200 Subject: [PATCH 3/7] Merge duplicate changelog groups and list instrumentation ownership as a change Drops the llama.cpp line about automatic prompt and reply attachments, which the explicit-attachments change removed. --- CHANGELOG.md | 129 +++++++++++++++++++++++---------------------------- 1 file changed, 58 insertions(+), 71 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 780819a..e3df8bf 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,38 +5,48 @@ under Unreleased and move into a version section at release time. ## Unreleased +### Added + +- `mlx_whisper` and `faster_whisper` integrations track local Whisper model + loads and transcriptions, including faster-whisper's + `BatchedInferencePipeline`. Transcriptions record duration, language, word + count and audio metadata. Audio and transcript attachments must be supplied + explicitly through the manual tracking API. See docs/whisper.md. +- The OpenAI integration now tracks `responses.create()` for synchronous and + asynchronous clients, including streaming. Records input/output token usage, + cached and reasoning tokens, response status or incomplete reason, resolved + model metadata, and time to first output delta for streams. Older OpenAI SDKs + without Responses remain supported. +- OpenAI sync and async `embeddings.create()` instrumentation records latency, + input token usage, batch size, vector dimensions, model metadata and errors. + Embedding vectors and raw inputs are never attached by this adapter. + `EmbeddingOutputMeta` now accepts optional `tokens_in` for analytics. +- Anthropic native `messages.stream()` helpers are now instrumented for sync + and async clients, including event iteration, `text_stream`, and final-message + helpers, with the shared streaming lifecycle contract. +- Process-wide integrations and hub patches now support sequential SDK client + replacement after the previous owner closes. Reinitialization replaces a + closed default. Existing models and provider clients keep their original + destination and must be recreated. Attempts to use a closed telemetry + destination warn once instead of silently dropping inference and error + events. + ### Changed - The llama.cpp Python integration is now named `llama_cpp` in Python, CLI, and environment configuration. `gguf` remains a compatibility alias; `all` selects the integration once under its new name. Model format metadata remains `gguf`. - - Automatic integrations no longer attach raw payloads, including GGUF prompts, chat messages and replies. `attachments_enabled=True` enables uploads only for attachments explicitly passed to `track_inference(attachments=[...])`. Apps relying on automatic GGUF capture must supply attachments explicitly. - -### Added - -- `mlx_whisper` and `faster_whisper` integrations track local Whisper model - loads and transcriptions, including faster-whisper's - `BatchedInferencePipeline`. Transcriptions record duration, language, word - count and audio metadata. Audio and transcript attachments must be supplied - explicitly through the manual tracking API. See docs/whisper.md. - -### Fixed - -- Changing a model's metadata (for example `register_model(..., version="v2")`) - now takes effect after a restart. With offline persistence on (the default), - the model registry saved by an earlier process kept the first metadata ever - registered for each model on that machine, so later changes were ignored. - This includes anthropic models already saved as `"unknown"`. - -- `import wildedge` no longer imports every installed ML framework and API - client. Each library is imported when its integration is activated or a - model from it is registered, so SDK import is faster and a broken unrelated - package no longer stops the SDK from starting. +- Enabling an integration or hub on a second live client now raises + `RuntimeError` while another client owns process-wide instrumentation. This + includes `wildedge.init(dsn=..., integrations=[...])` under `wildedge run`. + Previously the second client's patches were skipped without a warning and + automatic events kept going to the first client. Call `init()` without `dsn` + to reuse the client `wildedge run` installed, or close the owner first. - Quantization labels are defined once in `wildedge.quantizations` and used by every integration. Behaviour changes: - MLX-LM reports N-bit weights as `int4`/`int8`, like Transformers, instead @@ -46,73 +56,50 @@ under Unreleased and move into a version section at release time. reports `int8`. - faster-whisper reports weight precision (`int8`, `f16`) instead of CTranslate2 compute types such as `int8_float32`. +- The ultralytics integration now requires ultralytics 8.0.200 or later + (was 8.0.0). Earlier 8.0.x releases keep their helpers under + `ultralytics.yolo.utils`, and the integration turned itself off on them + without a word. `instrument("ultralytics")` now logs a warning naming the + installed version instead. + +### Fixed +- The llama.cpp integration now tracks `Llama.create_chat_completion()` and + `Llama.create_completion()`, streaming or not. It used to patch only + `Llama.__call__`, so chat apps on llama-cpp-python reported model loads but + no inference events. It now patches `create_completion`, which every entry + point runs, so each call is tracked once. +- llama.cpp inference events now include the stop reason for non-streamed + calls, the generation config (`temperature`, `top_p`, `top_k`, `max_tokens`, + `repeat_penalty`, penalties, `seed`, stop sequence count), and, for chat + calls, `prompt_type="chat"` and `turn_index` measured on the last user + message. +- `import wildedge` no longer imports every installed ML framework and API + client. Each library is imported when its integration is activated or a + model from it is registered, so SDK import is faster and a broken unrelated + package no longer stops the SDK from starting. +- Changing a model's metadata (for example `register_model(..., version="v2")`) + now takes effect after a restart. With offline persistence on (the default), + the model registry saved by an earlier process kept the first metadata ever + registered for each model on that machine, so later changes were ignored. + This includes anthropic models already saved as `"unknown"`. - MLX-LM models now report the device they run on (`mps` for the Apple GPU) instead of always `cpu`. Accelerator names are defined once in `wildedge.accelerators`, and PyTorch, Transformers, Ultralytics, TensorFlow and Keras share their device detection. - -- 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 metadata, and explicit model IDs retain priority. - - Ultralytics `model.predict()` now records inference telemetry. Instrumentation patches `predict`, which `model(...)` delegates to, so both entry points are tracked exactly once. - - Streaming wrappers now finalize once across exhaustion, explicit closure, cancellation, and iterator errors. Early closure/cancellation records an unsuccessful inference with partial metadata when available. TTFT ignores lifecycle/role-only chunks; telemetry callbacks cannot break iteration and retain the trace context captured at stream creation. Remote API streams ending without their completion marker record `STREAM_INCOMPLETE`. - -### Added - -- Anthropic native `messages.stream()` helpers are now instrumented for sync - and async clients, including event iteration, `text_stream`, and final-message - helpers, with the shared streaming lifecycle contract. - -- OpenAI sync and async `embeddings.create()` instrumentation records latency, - input token usage, batch size, vector dimensions, model metadata and errors. - Embedding vectors and raw inputs are never attached by this adapter. - `EmbeddingOutputMeta` now accepts optional `tokens_in` for analytics. - -- The OpenAI integration now tracks `responses.create()` for synchronous and - asynchronous clients, including streaming. Records input/output token usage, - cached and reasoning tokens, response status or incomplete reason, resolved - model metadata, and time to first output delta for streams. Older OpenAI SDKs - without Responses remain supported. - -### Changed - -- The ultralytics integration now requires ultralytics 8.0.200 or later - (was 8.0.0). Earlier 8.0.x releases keep their helpers under - `ultralytics.yolo.utils`, and the integration turned itself off on them - without a word. `instrument("ultralytics")` now logs a warning naming the - installed version instead. - -### Fixed - -- The gguf integration now tracks `Llama.create_chat_completion()` and - `Llama.create_completion()`, streaming or not. It used to patch only - `Llama.__call__`, so chat apps on llama-cpp-python reported model loads but - no inference events. It now patches `create_completion`, which every entry - point runs, so each call is tracked once. -- gguf inference events now include the stop reason for non-streamed calls, - the generation config (`temperature`, `top_p`, `top_k`, `max_tokens`, - `repeat_penalty`, penalties, `seed`, stop sequence count), and, for chat - calls, `prompt_type="chat"` and `turn_index` measured on the last user - message. With attachments enabled, the prompt or chat messages and the reply - are attached. - A span attribute whose value is a list, dict or other non-scalar no longer gets the whole event batch rejected. Ingest only accepts scalar attribute values and answered 422 for the batch, dropping unrelated loads, inferences From cb23ef1836c6cc8802e57a2acb0475efe5dc5683 Mon Sep 17 00:00:00 2001 From: Piotr Duda Date: Wed, 21 Oct 2026 19:06:57 +0200 Subject: [PATCH 4/7] Serialize consumer drains so flush() cannot resend an in-flight batch The fork hooks hold the drain lock across fork() so a child never inherits it locked. --- CHANGELOG.md | 5 +++ tests/test_consumer.py | 69 ++++++++++++++++++++++++++++++++++++++++++ wildedge/consumer.py | 26 ++++++++++++++-- 3 files changed, 98 insertions(+), 2 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index e3df8bf..3f1b0f5 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -125,6 +125,11 @@ under Unreleased and move into a version section at release time. tracked call of its pipeline; other models the pipeline runs, and direct calls to the model, are still tracked. Generator and dataset inputs, which run lazily, are not covered yet (#78). +- `flush()` no longer sends a batch the background sender is already sending. + Both used to send the same events and then each removed a batch from the + queue, so events were duplicated and, depending on timing, later events + could be removed without being sent. This showed up when a process started + with events saved by an earlier run and flushed soon after. ## 0.2.2 - 2026-09-30 diff --git a/tests/test_consumer.py b/tests/test_consumer.py index 3d61885..12846e0 100644 --- a/tests/test_consumer.py +++ b/tests/test_consumer.py @@ -1,6 +1,7 @@ """Tests for the background consumer.""" import os +import threading from unittest.mock import MagicMock, patch import pytest @@ -346,6 +347,48 @@ def fake_register(fn, *args, **kwargs): assert registered["fn"] == consumer.flush assert registered["args"] == (constants.DEFAULT_SHUTDOWN_FLUSH_TIMEOUT_SEC,) + def test_flush_does_not_resend_a_batch_already_in_flight(self, monkeypatch): + monkeypatch.setattr(Consumer, "run", lambda self: None) + queue = EventQueue(max_size=100) + for i in range(10): + queue.add({"event_id": str(i), "event_type": "inference", "model_id": "m"}) + sending = threading.Event() + release = threading.Event() + sent: list[str] = [] + + def slow_send(batch): + sent.extend(e["event_id"] for e in batch["events"]) + sending.set() + release.wait(5) + return make_success_response(len(batch["events"])) + + mock_transmitter = MagicMock(spec=Transmitter) + mock_transmitter.send.side_effect = slow_send + consumer = self._make_consumer(queue, mock_transmitter, batch_size=10) + + background = threading.Thread(target=consumer.drain_once) + background.start() + assert sending.wait(5) + flusher = threading.Thread(target=consumer.flush, kwargs={"timeout": 5}) + flusher.start() + release.set() + background.join(5) + flusher.join(5) + + assert sorted(sent, key=int) == [str(i) for i in range(10)] + assert queue.length() == 0 + + def test_drain_once_gives_up_when_lock_wait_times_out(self, monkeypatch): + monkeypatch.setattr(Consumer, "run", lambda self: None) + queue = EventQueue(max_size=100) + queue.add({"event_id": "e1", "event_type": "inference", "model_id": "m"}) + mock_transmitter = MagicMock(spec=Transmitter) + consumer = self._make_consumer(queue, mock_transmitter) + + with consumer.drain_lock: + assert consumer.drain_once(timeout=0.01) is False + mock_transmitter.send.assert_not_called() + class TestConsumerForkSafety: def setup_method(self): @@ -442,6 +485,32 @@ def test_resume_registers_atexit(self, monkeypatch): assert any(fn == consumer.flush for fn, _ in registered) + def test_pause_holds_drain_lock_until_resume(self, monkeypatch): + monkeypatch.setattr(Consumer, "run", lambda self: None) + consumer = self._make_consumer( + EventQueue(max_size=100), MagicMock(spec=Transmitter) + ) + + consumer._pause() + assert consumer.drain_lock.locked() + consumer._resume() + assert not consumer.drain_lock.locked() + + def test_resume_replaces_lock_held_by_in_flight_send(self, monkeypatch): + monkeypatch.setattr(Consumer, "run", lambda self: None) + consumer = self._make_consumer( + EventQueue(max_size=100), MagicMock(spec=Transmitter) + ) + stuck = consumer.drain_lock + # A send that outlived _pause() still holds the lock. + stuck.acquire() + consumer.fork_holds_drain_lock = False + consumer._resume() + + assert consumer.drain_lock is not stuck + assert not consumer.drain_lock.locked() + stuck.release() + class TestForkRegistration: @pytest.mark.skipif( diff --git a/wildedge/consumer.py b/wildedge/consumer.py index ef8c15d..44ed595 100644 --- a/wildedge/consumer.py +++ b/wildedge/consumer.py @@ -50,6 +50,10 @@ def __init__( self.stop_event = threading.Event() self.stopped = False + # One drain at a time: flush() on the caller's thread and the background + # thread would otherwise send the same batch and both remove it. + self.drain_lock = threading.Lock() + self.fork_holds_drain_lock = False self.backoff = constants.BACKOFF_MIN self.created_at = datetime.now(timezone.utc) @@ -133,7 +137,16 @@ def dead_letter_and_drop( self.queue.remove_first_n(len(events)) self.notify_delivery_failure(reason, len(events)) - def drain_once(self) -> bool: + def drain_once(self, timeout: float = -1) -> bool: + """Send one batch. Returns False if no progress was made.""" + if not self.drain_lock.acquire(timeout=timeout): + return False + try: + return self.drain_once_locked() + finally: + self.drain_lock.release() + + def drain_once_locked(self) -> bool: events = self.queue.peek_many(self.batch_size) if not events: return False @@ -218,7 +231,7 @@ def flush(self, timeout: float = 5.0) -> None: deadline = time.monotonic() + timeout backoff = constants.BACKOFF_MIN while self.queue.length() > 0 and time.monotonic() < deadline: - progressed = self.drain_once() + progressed = self.drain_once(timeout=max(0.0, deadline - time.monotonic())) if self.queue.length() == 0: break remaining = deadline - time.monotonic() @@ -243,6 +256,9 @@ def _pause(self) -> None: """ self.stop_event.set() self.thread.join(timeout=1.0) + # Hold the drain lock across fork() so the child never inherits it + # locked by a thread that does not exist there. + self.fork_holds_drain_lock = self.drain_lock.acquire(timeout=1.0) # Reset so _resume() can start a fresh thread in parent and child. self.stopped = False @@ -253,6 +269,12 @@ def _resume(self) -> None: Creates a new Event and Thread so parent and child each get an independent consumer. """ + if self.fork_holds_drain_lock: + self.drain_lock.release() + self.fork_holds_drain_lock = False + else: + # A send outlived _pause(). Start over rather than wait on it. + self.drain_lock = threading.Lock() self.stop_event = threading.Event() self.backoff = constants.BACKOFF_MIN self._held_snapshot = None From 0e24083f9d552162134e02d952b80704fdf6b72f Mon Sep 17 00:00:00 2001 From: Piotr Duda Date: Wed, 21 Oct 2026 19:07:25 +0200 Subject: [PATCH 5/7] Add streaming and whisper docs to llms.txt --- scripts/build_llms_txt.py | 2 ++ 1 file changed, 2 insertions(+) diff --git a/scripts/build_llms_txt.py b/scripts/build_llms_txt.py index 66f0cad..d4eaa3e 100644 --- a/scripts/build_llms_txt.py +++ b/scripts/build_llms_txt.py @@ -24,6 +24,8 @@ ("docs/manual-tracking.md", "manual-tracking", "Manual tracking"), ("docs/llm_api.md", "llm_api", "LLM API tracking"), ("docs/providers.md", "providers", "Providers"), + ("docs/streaming.md", "streaming", "Streaming lifecycle"), + ("docs/whisper.md", "whisper", "Whisper"), ("docs/compatibility.md", "compatibility", "Compatibility matrix"), ] From fd90cd05ea3e762a5a2b3f8be64f8420b035c6bd Mon Sep 17 00:00:00 2001 From: Piotr Duda Date: Wed, 21 Oct 2026 19:14:34 +0200 Subject: [PATCH 6/7] 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. --- CHANGELOG.md | 13 ++--- docs/deployment.md | 20 ++++--- docs/manual-tracking.md | 4 +- tests/conftest.py | 1 + tests/test_cli.py | 32 +++++++++++- tests/test_instrumentation_ownership.py | 69 ++++++++++++++++++++++++- wildedge/client.py | 38 ++++++++++++-- wildedge/convenience.py | 44 ++++++++++++---- wildedge/instrumentation.py | 17 +++++- wildedge/runtime/bootstrap.py | 5 ++ 10 files changed, 211 insertions(+), 32 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 3f1b0f5..e2f671a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -41,12 +41,13 @@ under Unreleased and move into a version section at release time. chat messages and replies. `attachments_enabled=True` enables uploads only for attachments explicitly passed to `track_inference(attachments=[...])`. Apps relying on automatic GGUF capture must supply attachments explicitly. -- Enabling an integration or hub on a second live client now raises - `RuntimeError` while another client owns process-wide instrumentation. This - includes `wildedge.init(dsn=..., integrations=[...])` under `wildedge run`. - Previously the second client's patches were skipped without a warning and - automatic events kept going to the first client. Call `init()` without `dsn` - to reuse the client `wildedge run` installed, or close the owner first. +- `wildedge.init(dsn=...)` reuses the existing default client when the DSN + points to the same project, for example `dsn=os.environ["WILDEDGE_DSN"]` + under `wildedge run`. It used to create a second client. +- Enabling an integration or hub on a second client while another live client + owns process-wide instrumentation now logs a warning. Automatic events keep + going to the owner's project, as before, but this used to happen without a + word. With `wildedge run --strict-integrations` it raises `RuntimeError`. - Quantization labels are defined once in `wildedge.quantizations` and used by every integration. Behaviour changes: - MLX-LM reports N-bit weights as `int4`/`int8`, like Transformers, instead diff --git a/docs/deployment.md b/docs/deployment.md index 40829c6..d7f1a1f 100644 --- a/docs/deployment.md +++ b/docs/deployment.md @@ -16,8 +16,9 @@ There are three ways a process gets its client, in order of coverage: All three produce the same thing: one process-wide default client that `wildedge.span()`, `wildedge.register_model()` and the rest delegate to. -`init()` without `dsn` reuses whatever client already exists, so code written -for in-process init runs unchanged under `wildedge run`. +`init()` without `dsn`, or with the DSN that client already uses, reuses +whatever client already exists, so code written for in-process init runs +unchanged under `wildedge run`. The lazy mode configures itself from the environment: `WILDEDGE_DSN`, `WILDEDGE_INTEGRATIONS`, `WILDEDGE_HUBS`. Unset integration variables mean @@ -99,12 +100,15 @@ them unwrapped or unset `WILDEDGE_DSN` there. ## One client per process - 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. + owns process-wide auto-instrumentation. When another client enables an + integration or hub while that owner is live, it logs a warning and + automatic events keep going to the owner's project. The new client still + sends its manual tracking. With `wildedge run --strict-integrations`, the + conflict raises `RuntimeError` instead. Manual tracking does not claim + ownership. +- `init()` reuses the live default client unless you pass a `dsn` for a + different project, 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 diff --git a/docs/manual-tracking.md b/docs/manual-tracking.md index cd185a8..0bcc769 100644 --- a/docs/manual-tracking.md +++ b/docs/manual-tracking.md @@ -26,8 +26,8 @@ with wildedge.trace(run_id="run-123"): The default client comes from wherever initialization happened first: - `wildedge run` installs one before your code loads. A later - `wildedge.init()` without `dsn` reuses it, so the same code works with or - without the CLI wrapper. + `wildedge.init()` without `dsn`, or with the same DSN, reuses it, so the + same code works with or without the CLI wrapper. - `wildedge.init(...)` creates one (or reuses the existing default) and registers it. - Any module-level call (`wildedge.span`, `wildedge.register_model`, ...) diff --git a/tests/conftest.py b/tests/conftest.py index e9f04ae..8b011f3 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -131,4 +131,5 @@ def client_with_stubbed_runtime(): def isolate_instrumentation_owner(monkeypatch): monkeypatch.setattr(instrumentation, "_owner", None) monkeypatch.setattr(instrumentation, "_enabled", set()) + monkeypatch.setattr(instrumentation, "_strict_ownership", False) monkeypatch.setattr(huggingface, "_client_route", None) diff --git a/tests/test_cli.py b/tests/test_cli.py index 9162a56..88e12bf 100644 --- a/tests/test_cli.py +++ b/tests/test_cli.py @@ -6,7 +6,7 @@ import pytest -from wildedge import cli, constants +from wildedge import cli, constants, instrumentation from wildedge.defaults import peek_default_client from wildedge.integrations.registry import IntegrationSpec from wildedge.platforms.device_info import DeviceInfo @@ -237,6 +237,36 @@ def instrument(self, name): # type: ignore[no-untyped-def] bootstrap.install_runtime() +@pytest.mark.parametrize("strict", ["0", "1"]) +def test_install_runtime_records_strict_ownership(monkeypatch, strict): + class FakeWildEdge: + SUPPORTED_INTEGRATIONS = {"onnx"} + + def __init__(self, *, dsn, app_version, debug, sampling_interval_s=None): # type: ignore[no-untyped-def] + pass + + def instrument(self, name): # type: ignore[no-untyped-def] + pass + + def flush(self, timeout): # type: ignore[no-untyped-def] + pass + + def close(self): # type: ignore[no-untyped-def] + pass + + monkeypatch.setattr(bootstrap, "WildEdge", FakeWildEdge) + monkeypatch.setenv(constants.ENV_DSN, "https://secret@ingest.wildedge.dev/key") + monkeypatch.setenv(constants.ENV_INTEGRATIONS, "onnx") + monkeypatch.setenv(constants.ENV_STRICT_INTEGRATIONS, strict) + monkeypatch.setattr(bootstrap.importlib.util, "find_spec", lambda _: object()) + + context = bootstrap.install_runtime() + try: + assert instrumentation.strict_ownership() is (strict == "1") + finally: + context.shutdown() + + def test_doctor_reports_missing_dsn_and_unknown_integration(monkeypatch, capsys): monkeypatch.delenv("WILDEDGE_DSN", raising=False) rc = cli.main(["doctor", "--integrations", "madeup"]) diff --git a/tests/test_instrumentation_ownership.py b/tests/test_instrumentation_ownership.py index 2ac27dc..45f3ad1 100644 --- a/tests/test_instrumentation_ownership.py +++ b/tests/test_instrumentation_ownership.py @@ -140,9 +140,32 @@ def test_close_is_idempotent(clients): client.consumer.close.assert_called_once() -def test_init_conflict_cleans_up_new_client_without_stopping_owner_sampler( +def test_init_with_other_dsn_warns_and_leaves_tracking_with_owner( + clients, monkeypatch, caplog +): + caplog.set_level("WARNING", logger="wildedge") + first = clients() + route = 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: + result = wildedge.init( + dsn="https://other@localhost/other", integrations=["onnx"] + ) + stop.assert_not_called() + assert result is second + assert not second.closed + assert not first.closed + assert route() is first + assert convenience.peek_default_client() is second + assert [r for r in caplog.records if "already owns automatic tracking" in r.message] + + +def test_strict_ownership_conflict_raises_and_cleans_up_new_client( clients, monkeypatch ): + instrumentation.set_strict_ownership(True) first = clients() claim_instrumentation(first, "onnx") set_default_client(first) @@ -157,6 +180,50 @@ def test_init_conflict_cleans_up_new_client_without_stopping_owner_sampler( assert convenience.peek_default_client() is first +def test_init_with_owner_dsn_reuses_owner(clients, monkeypatch, caplog): + caplog.set_level("WARNING", logger="wildedge") + first = clients() + first.instrument("onnx") + set_default_client(first) + monkeypatch.setattr( + convenience, "WildEdge", MagicMock(side_effect=AssertionError("new client")) + ) + assert ( + wildedge.init(dsn="https://test@localhost/test", integrations=["onnx"]) is first + ) + assert not [r for r in caplog.records if "ignoring" in r.message] + + +def test_init_with_dsn_none_reuses_owner_of_env_dsn(clients, monkeypatch): + first = clients() + set_default_client(first) + monkeypatch.setenv("WILDEDGE_DSN", "https://test@localhost/test") + monkeypatch.setattr( + convenience, "WildEdge", MagicMock(side_effect=AssertionError("new client")) + ) + assert wildedge.init(dsn=None) is first + + +def test_hub_conflict_warns_and_skips(clients, monkeypatch, caplog): + caplog.set_level("WARNING", logger="wildedge") + installs = [] + + class Tracker: + def can_install(self): + return True + + def install_patch(self, route): + installs.append(route) + + monkeypatch.setitem(WildEdge.HUB_TRACKER_CLASSES, "huggingface", Tracker) + first, second = clients(), clients() + first.instrument(None, hubs=["huggingface"]) + second.instrument(None, hubs=["huggingface"]) + assert len(installs) == 1 + assert "huggingface" not in second.hub_trackers + assert [r for r in caplog.records if "already owns automatic tracking" in r.message] + + @pytest.mark.parametrize("hub", ["huggingface", "torchhub"]) def test_hub_factory_route_follows_replacement(clients, monkeypatch, hub): routes = [] diff --git a/wildedge/client.py b/wildedge/client.py index c0a0f8d..83862ee 100644 --- a/wildedge/client.py +++ b/wildedge/client.py @@ -23,7 +23,13 @@ from wildedge.events.span import SpanKind, SpanStatus from wildedge.hubs.base import BaseHubTracker from wildedge.hubs.registry import HUB_SPECS, supported_hubs -from wildedge.instrumentation import claim_instrumentation, has_other_live_owner +from wildedge.instrumentation import ( + ClientRoute, + InstrumentationOwnedError, + claim_instrumentation, + has_other_live_owner, + strict_ownership, +) from wildedge.integrations.base import BaseExtractor from wildedge.integrations.registry import ( INTEGRATION_SPECS, @@ -280,10 +286,14 @@ def __init__( dsn = env.dsn debug = env.debug self.noop = False + # (secret, host, project_key), so init(dsn=...) can tell when a + # requested destination matches this client. None for a no-op client. + self.destination: tuple[str, str, str] | None = None if not dsn: self._init_noop(debug=debug, device=device) return api_key, host, project_key = parse_dsn(dsn) + self.destination = (api_key, host, project_key) app_identity = resolve_app_identity( explicit=env.app_identity, project_key=project_key, @@ -689,11 +699,31 @@ def _activate_hub(self, hub_name: str) -> None: "wildedge: hub '%s' library not installed; skipping", hub_name ) return - tracker.install_patch(claim_instrumentation(self, "hub:" + hub_name)) + route = self._claim_instrumentation("hub:" + hub_name) + if route is None: + return + tracker.install_patch(route) self.hub_trackers[hub_name] = tracker if self.debug: logger.debug("wildedge: hub tracker '%s' activated", hub_name) + def _claim_instrumentation(self, name: str) -> ClientRoute | None: + """Claim process-wide instrumentation, or warn and skip if owned.""" + try: + return claim_instrumentation(self, name) + except InstrumentationOwnedError: + if strict_ownership(): + raise + logger.warning( + "wildedge: another WildEdge client (for example the one " + "`wildedge run` installed) already owns automatic tracking, so " + "'%s' events keep going to that client's project. Call " + "wildedge.init() without dsn to reuse that client, or close it " + "before enabling integrations on this one.", + name, + ) + return None + def _snapshot_hub_caches(self) -> dict[str, dict[str, int]]: """Return a before-snapshot of all active hub cache directories.""" return { @@ -846,7 +876,9 @@ def instrument( logger.debug(LOG_INSTRUMENT_TORCH_KERAS, integration) else: installer = self.PATCH_INSTALLERS[integration] - installer(claim_instrumentation(self, integration)) + route = self._claim_instrumentation(integration) + if route is not None: + installer(route) for hub_name in hubs or []: self._activate_hub(hub_name) diff --git a/wildedge/convenience.py b/wildedge/convenience.py index 4086d8d..1f15de9 100644 --- a/wildedge/convenience.py +++ b/wildedge/convenience.py @@ -3,9 +3,10 @@ from collections.abc import Iterable from typing import Any -from wildedge.client import WildEdge +from wildedge.client import WildEdge, parse_dsn from wildedge.defaults import peek_default_client, set_default_client from wildedge.logging import logger +from wildedge.settings import read_client_env def _normalize_list(value: str | Iterable[str] | None) -> list[str]: @@ -16,6 +17,20 @@ def _normalize_list(value: str | Iterable[str] | None) -> list[str]: return [item for item in value if item] +def _same_destination(client: WildEdge, dsn: str | None) -> bool: + """True when ``dsn`` (or WILDEDGE_DSN) points where ``client`` sends.""" + destination = getattr(client, "destination", None) + if destination is None: + return False + resolved = read_client_env(dsn=dsn).dsn + if not resolved: + return False + try: + return parse_dsn(resolved) == destination + except ValueError: + return False + + def init( *, integrations: str | Iterable[str] | None = None, @@ -26,23 +41,32 @@ def init( Initialize the process default client and instrument integrations. 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 after instrumentation - succeeds. A closed default is replaced. Another live instrumentation owner - must be closed before enabling process-wide patches on a new client. + run`` before user code loaded) and no ``dsn`` is passed, or ``dsn`` points + to the same project, that client is reused: the requested integrations are + applied to it (instrumenting is idempotent per process) and it is returned. + A ``dsn`` for another project constructs a fresh client and makes it the new + default. A closed default is replaced. While another live client owns + process-wide instrumentation, the new client logs a warning and leaves + automatic tracking with that owner. With ``wildedge run + --strict-integrations`` it raises ``RuntimeError`` instead. Additional keyword arguments are forwarded to WildEdge(...) when a new client is constructed. """ - client = None if "dsn" in kwargs else peek_default_client() + client = peek_default_client() if client is not None and client.closed: client = None - if client is not None and kwargs: + if ( + client is not None + and "dsn" in kwargs + and not _same_destination(client, kwargs["dsn"]) + ): + client = None + ignored = sorted(key for key in kwargs if key != "dsn") + if client is not None and ignored: logger.warning( "wildedge: init() reusing the existing default client; ignoring %s", - ", ".join(sorted(kwargs)), + ", ".join(ignored), ) created = client is None if created: diff --git a/wildedge/instrumentation.py b/wildedge/instrumentation.py index 9b988b2..25dbdcb 100644 --- a/wildedge/instrumentation.py +++ b/wildedge/instrumentation.py @@ -15,6 +15,21 @@ _lock = threading.Lock() _owner: weakref.ReferenceType[WildEdge] | None = None _enabled: set[str] = set() +_strict_ownership = False + + +class InstrumentationOwnedError(RuntimeError): + """Another live client already owns process-wide instrumentation.""" + + +def set_strict_ownership(strict: bool) -> None: + """Raise on ownership conflicts instead of warning (`--strict-integrations`).""" + global _strict_ownership + _strict_ownership = strict + + +def strict_ownership() -> bool: + return _strict_ownership class ClientRoute: @@ -67,7 +82,7 @@ def claim_instrumentation(client: WildEdge, integration: str) -> ClientRoute: 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( + raise InstrumentationOwnedError( "Auto-instrumentation is owned by another live WildEdge client; " "close that client before enabling instrumentation on its replacement" ) diff --git a/wildedge/runtime/bootstrap.py b/wildedge/runtime/bootstrap.py index 63e0ee4..308b9b6 100644 --- a/wildedge/runtime/bootstrap.py +++ b/wildedge/runtime/bootstrap.py @@ -16,6 +16,7 @@ from wildedge.constants import ENV_DSN, WILDEDGE_AUTOLOAD from wildedge.defaults import set_default_client from wildedge.hubs.registry import HUBS_BY_NAME, supported_hubs +from wildedge.instrumentation import set_strict_ownership from wildedge.integrations.registry import INTEGRATIONS_BY_NAME, supported_integrations from wildedge.settings import read_runtime_env @@ -208,6 +209,10 @@ def install_runtime(*, install_signal_handlers: bool = True) -> RuntimeContext: file=os.sys.stderr, ) + # The app may call init() with its own DSN later. Under + # --strict-integrations an ownership conflict then raises instead of warning. + set_strict_ownership(env.strict_integrations) + if env.strict_integrations: failures = [row for row in statuses if row["status"] in STRICT_FAILURE_STATUSES] if failures: From d45c19a12d6aa21b6afe0d6896fed241ba60a7be Mon Sep 17 00:00:00 2001 From: Piotr Duda Date: Wed, 21 Oct 2026 19:15:09 +0200 Subject: [PATCH 7/7] Release 0.3.0 --- CHANGELOG.md | 2 ++ pyproject.toml | 2 +- uv.lock | 2 +- 3 files changed, 4 insertions(+), 2 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index e2f671a..7963027 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,6 +5,8 @@ under Unreleased and move into a version section at release time. ## Unreleased +## 0.3.0 - 2026-10-21 + ### Added - `mlx_whisper` and `faster_whisper` integrations track local Whisper model diff --git a/pyproject.toml b/pyproject.toml index 71f5656..7127eec 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,6 +1,6 @@ [project] name = "wildedge-sdk" -version = "0.2.2" +version = "0.3.0" description = "ML inference monitoring for Python: on-device and remote models" readme = "README.md" requires-python = ">=3.10" diff --git a/uv.lock b/uv.lock index 8ff0ac1..a33da49 100644 --- a/uv.lock +++ b/uv.lock @@ -419,7 +419,7 @@ wheels = [ [[package]] name = "wildedge-sdk" -version = "0.2.2" +version = "0.3.0" source = { editable = "." } [package.dev-dependencies]