python-wrap 0.2.1__py3-none-any.whl → 0.4.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- python_wrap/__init__.py +348 -1
- python_wrap/__main__.py +57 -0
- python_wrap/_backend.py +133 -0
- python_wrap/_buckets.py +162 -0
- python_wrap/_core.py +12 -3
- python_wrap/_data/agent_guide.md +103 -0
- python_wrap/_data/recipes.json +703 -0
- python_wrap/_fork.py +113 -0
- python_wrap/_integration.py +29 -0
- python_wrap/_runtime.py +157 -0
- python_wrap/adapters/__init__.py +101 -0
- python_wrap/adapters/_frameworks.py +251 -0
- python_wrap/adapters/_sdk.py +1978 -0
- python_wrap/adapters/anthropic.py +139 -0
- python_wrap/adapters/langchain.py +288 -0
- python_wrap/adapters/openai.py +169 -0
- python_wrap/adapters/openai_agents.py +468 -0
- python_wrap/adapters/pydantic_ai.py +459 -0
- python_wrap/adaptive.py +605 -0
- python_wrap/agents.py +2503 -0
- python_wrap/alerts.py +293 -0
- python_wrap/async_cache.py +745 -0
- python_wrap/batching.py +17 -4
- python_wrap/buffering.py +952 -0
- python_wrap/bulkhead.py +58 -6
- python_wrap/caching.py +425 -56
- python_wrap/celery.py +528 -0
- python_wrap/chaos.py +519 -0
- python_wrap/circuit.py +454 -23
- python_wrap/compat.py +267 -0
- python_wrap/concurrency.py +82 -1746
- python_wrap/config.py +25 -4
- python_wrap/coordination.py +638 -0
- python_wrap/credentials.py +126 -0
- python_wrap/dashboard.py +358 -0
- python_wrap/debounce.py +538 -0
- python_wrap/django.py +100 -0
- python_wrap/doctor.py +599 -0
- python_wrap/events.py +145 -4
- python_wrap/exporters.py +663 -0
- python_wrap/fastapi.py +81 -0
- python_wrap/flask.py +61 -0
- python_wrap/genai.py +1101 -0
- python_wrap/health.py +187 -0
- python_wrap/http.py +940 -0
- python_wrap/idempotency.py +446 -0
- python_wrap/introspect.py +738 -0
- python_wrap/lifecycle.py +620 -0
- python_wrap/llm.py +2574 -0
- python_wrap/llm_cassette.py +948 -0
- python_wrap/llm_http_chaos.py +326 -0
- python_wrap/llm_shared.py +772 -0
- python_wrap/llm_testing.py +990 -0
- python_wrap/llm_validate.py +383 -0
- python_wrap/local_state.py +395 -0
- python_wrap/logs.py +82 -26
- python_wrap/mcp.py +490 -0
- python_wrap/mcp_guard.py +357 -0
- python_wrap/metrics.py +6 -3
- python_wrap/migrate.py +1452 -0
- python_wrap/observability.py +484 -0
- python_wrap/periodic.py +24 -2
- python_wrap/policies.py +396 -0
- python_wrap/policy.py +14 -0
- python_wrap/predicates.py +276 -0
- python_wrap/presets.py +378 -0
- python_wrap/processing.py +227 -0
- python_wrap/propagation.py +62 -0
- python_wrap/pytest_plugin.py +85 -0
- python_wrap/quotas.py +319 -0
- python_wrap/ratelimit.py +560 -0
- python_wrap/redaction.py +228 -0
- python_wrap/retry.py +448 -70
- python_wrap/shared.py +653 -0
- python_wrap/singleflight.py +255 -0
- python_wrap/slow.py +72 -0
- python_wrap/stores.py +168 -0
- python_wrap/switches.py +164 -0
- python_wrap/testing.py +34 -8
- python_wrap/timeouts.py +874 -0
- python_wrap/timing.py +239 -17
- python_wrap/validation.py +187 -12
- python_wrap/web.py +723 -0
- {python_wrap-0.2.1.dist-info → python_wrap-0.4.0.dist-info}/METADATA +117 -7
- python_wrap-0.4.0.dist-info/RECORD +95 -0
- python_wrap-0.2.1.dist-info/RECORD +0 -29
- {python_wrap-0.2.1.dist-info → python_wrap-0.4.0.dist-info}/WHEEL +0 -0
- {python_wrap-0.2.1.dist-info → python_wrap-0.4.0.dist-info}/licenses/LICENSE +0 -0
|
@@ -0,0 +1,484 @@
|
|
|
1
|
+
"""Opt-in OpenTelemetry and Sentry adapters for decorator events.
|
|
2
|
+
|
|
3
|
+
Labels have bounded cardinality and never carry exception messages, arguments or
|
|
4
|
+
results: exceptions are reduced to their type names.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
import time
|
|
10
|
+
from typing import Any
|
|
11
|
+
|
|
12
|
+
from python_wrap import _fork
|
|
13
|
+
from python_wrap.events import Event, subscribe
|
|
14
|
+
|
|
15
|
+
__all__ = [
|
|
16
|
+
"COUNTERS",
|
|
17
|
+
"Breadcrumbs",
|
|
18
|
+
"GenAITelemetry",
|
|
19
|
+
"Telemetry",
|
|
20
|
+
"annotate_span",
|
|
21
|
+
"enable",
|
|
22
|
+
"enable_genai",
|
|
23
|
+
"genai_span_attributes",
|
|
24
|
+
"sentry_breadcrumbs",
|
|
25
|
+
]
|
|
26
|
+
# One table of event -> counter, used by `Telemetry` and checked against the Prometheus
|
|
27
|
+
# exporter in tests so the two cannot drift. Each row: legacy name, OpenTelemetry-style
|
|
28
|
+
# name, unit, description.
|
|
29
|
+
COUNTERS: dict[str, tuple[str, str, str, str]] = {
|
|
30
|
+
"retry.attempt_failed": (
|
|
31
|
+
"pw_retry_retries_total", "python_wrap.retry.retries", "{retry}",
|
|
32
|
+
"Failed attempts that were followed by a retry.",
|
|
33
|
+
),
|
|
34
|
+
"retry.gave_up": (
|
|
35
|
+
"pw_retry_gave_up_total", "python_wrap.retry.gave_up", "{call}",
|
|
36
|
+
"Calls whose retries were exhausted.",
|
|
37
|
+
),
|
|
38
|
+
"retry.budget_exhausted": (
|
|
39
|
+
"pw_retry_budget_exhausted_total", "python_wrap.retry.budget_exhausted", "{call}",
|
|
40
|
+
"Calls stopped because the retry budget was used up.",
|
|
41
|
+
),
|
|
42
|
+
"cache.hit": ("pw_cache_hits_total", "python_wrap.cache.hits", "{hit}", "Cache hits."),
|
|
43
|
+
"cache.miss": ("pw_cache_misses_total", "python_wrap.cache.misses", "{miss}", "Cache misses."),
|
|
44
|
+
"bulkhead.rejected": (
|
|
45
|
+
"pw_bulkhead_rejected_total", "python_wrap.bulkhead.rejected", "{call}",
|
|
46
|
+
"Calls refused by a full bulkhead.",
|
|
47
|
+
),
|
|
48
|
+
"circuit.rejected": (
|
|
49
|
+
"pw_breaker_rejected_total", "python_wrap.circuit.rejected", "{call}",
|
|
50
|
+
"Calls refused by an open circuit breaker.",
|
|
51
|
+
),
|
|
52
|
+
"rate_limit.rejected": (
|
|
53
|
+
"pw_rate_limit_rejected_total", "python_wrap.rate_limit.rejected", "{call}",
|
|
54
|
+
"Calls refused by a rate limiter.",
|
|
55
|
+
),
|
|
56
|
+
"timeout.expired": (
|
|
57
|
+
"pw_timeouts_total", "python_wrap.timeouts", "{call}", "Calls that hit their time limit."
|
|
58
|
+
),
|
|
59
|
+
"backend.error": (
|
|
60
|
+
"pw_backend_errors_total", "python_wrap.backend.errors", "{error}",
|
|
61
|
+
"Errors from a shared backend (function is the backend name).",
|
|
62
|
+
),
|
|
63
|
+
"rate_limit.store_error": (
|
|
64
|
+
"pw_rate_limit_store_errors_total", "python_wrap.rate_limit.store_errors", "{error}",
|
|
65
|
+
"Errors from a shared token window's storage.",
|
|
66
|
+
),
|
|
67
|
+
} # fmt: skip
|
|
68
|
+
WAIT = ("pw_limiter_wait_seconds", "python_wrap.rate_limit.wait")
|
|
69
|
+
BREAKER_STATE = ("pw_breaker_state", "python_wrap.circuit.state")
|
|
70
|
+
HEALTH_UP = ("pw_health_up", "python_wrap.health.up")
|
|
71
|
+
_STATES = {"closed": 0, "half_open": 1, "open": 2}
|
|
72
|
+
SPAN_MODES = ("events", "notifications", "off")
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
class Telemetry:
|
|
76
|
+
"""A subscription handle. Close removes instrumentation without changing providers.
|
|
77
|
+
|
|
78
|
+
Metrics: one counter per `COUNTERS` row, a histogram of rate-limiter waits, and two
|
|
79
|
+
observable gauges read at each collection: every breaker's state (0 closed,
|
|
80
|
+
1 half-open, 2 open; a shared breaker reports its state as this process sees it, so
|
|
81
|
+
every process converges within ``state_ttl``) and each health component's ``up``.
|
|
82
|
+
|
|
83
|
+
Traces: ``spans="events"`` (default) adds each event as a span event on the current
|
|
84
|
+
span; ``"notifications"`` opens and closes a ``pw.<event>`` span per event (the
|
|
85
|
+
pre-0.4.0b2 behaviour); ``"off"`` adds nothing. ``attempt_spans=True`` records one
|
|
86
|
+
span per retry attempt with its real duration and attempt number;
|
|
87
|
+
``wait_spans=True`` one span per rate-limiter wait.
|
|
88
|
+
"""
|
|
89
|
+
|
|
90
|
+
def __init__(
|
|
91
|
+
self,
|
|
92
|
+
tracer: Any,
|
|
93
|
+
meter: Any,
|
|
94
|
+
*,
|
|
95
|
+
max_functions: int = 100,
|
|
96
|
+
spans: str = "events",
|
|
97
|
+
attempt_spans: bool = False,
|
|
98
|
+
wait_spans: bool = False,
|
|
99
|
+
naming: str = "legacy",
|
|
100
|
+
current_span: Any = None,
|
|
101
|
+
registry: Any = None,
|
|
102
|
+
) -> None:
|
|
103
|
+
if max_functions < 1:
|
|
104
|
+
raise ValueError("max_functions must be positive")
|
|
105
|
+
if spans not in SPAN_MODES:
|
|
106
|
+
raise ValueError(f"spans must be one of {SPAN_MODES}")
|
|
107
|
+
if naming not in ("legacy", "otel"):
|
|
108
|
+
raise ValueError("naming must be 'legacy' or 'otel'")
|
|
109
|
+
self.tracer = tracer
|
|
110
|
+
self.limit = max_functions
|
|
111
|
+
self.spans, self.attempt_spans, self.wait_spans = spans, attempt_spans, wait_spans
|
|
112
|
+
self._current_span = current_span
|
|
113
|
+
self._names: set[str] = set()
|
|
114
|
+
self._lock = _fork.ForkSafeLock()
|
|
115
|
+
pick = 0 if naming == "legacy" else 1
|
|
116
|
+
self._counters: dict[str, Any] = {}
|
|
117
|
+
self._waits = self._states = self._health = None
|
|
118
|
+
if meter:
|
|
119
|
+
for event, row in COUNTERS.items():
|
|
120
|
+
if pick:
|
|
121
|
+
self._counters[event] = meter.create_counter(
|
|
122
|
+
row[1], unit=row[2], description=row[3]
|
|
123
|
+
)
|
|
124
|
+
else:
|
|
125
|
+
self._counters[event] = meter.create_counter(row[0])
|
|
126
|
+
self._waits = meter.create_histogram(WAIT[pick], unit="s")
|
|
127
|
+
self._states = meter.create_observable_gauge(
|
|
128
|
+
BREAKER_STATE[pick], callbacks=[self._observe_breakers]
|
|
129
|
+
)
|
|
130
|
+
self._registry = registry
|
|
131
|
+
if registry is not None:
|
|
132
|
+
self._health = meter.create_observable_gauge(
|
|
133
|
+
HEALTH_UP[pick], callbacks=[self._observe_health]
|
|
134
|
+
)
|
|
135
|
+
self._unsubscribe = subscribe(self._event)
|
|
136
|
+
self.closed = False
|
|
137
|
+
|
|
138
|
+
def _label(self, name: str) -> str:
|
|
139
|
+
with self._lock:
|
|
140
|
+
if name not in self._names:
|
|
141
|
+
if len(self._names) >= self.limit:
|
|
142
|
+
return "_other"
|
|
143
|
+
self._names.add(name)
|
|
144
|
+
return name
|
|
145
|
+
|
|
146
|
+
def _observe_breakers(self, options: Any = None) -> Any:
|
|
147
|
+
from opentelemetry.metrics import Observation
|
|
148
|
+
|
|
149
|
+
from python_wrap.circuit import _BREAKERS
|
|
150
|
+
|
|
151
|
+
if self.closed:
|
|
152
|
+
return []
|
|
153
|
+
out = []
|
|
154
|
+
for breaker in list(_BREAKERS):
|
|
155
|
+
try:
|
|
156
|
+
state = breaker.state.value
|
|
157
|
+
except Exception: # a store error must not break the whole collection
|
|
158
|
+
continue
|
|
159
|
+
out.append(Observation(_STATES[state], {"function": self._label(breaker.name)}))
|
|
160
|
+
return out
|
|
161
|
+
|
|
162
|
+
def _observe_health(self, options: Any = None) -> Any:
|
|
163
|
+
from opentelemetry.metrics import Observation
|
|
164
|
+
|
|
165
|
+
if self.closed:
|
|
166
|
+
return []
|
|
167
|
+
report = self._registry.report()
|
|
168
|
+
return [
|
|
169
|
+
Observation(1 if info.get("healthy") else 0, {"component": component})
|
|
170
|
+
for component, info in sorted(report.items())
|
|
171
|
+
]
|
|
172
|
+
|
|
173
|
+
def _span_back(self, name: str, seconds: Any, attributes: dict[str, Any]) -> None:
|
|
174
|
+
"""A span that ended now and lasted ``seconds`` (skipped when unknown)."""
|
|
175
|
+
if self.tracer is None or not isinstance(seconds, (int, float)) or seconds <= 0:
|
|
176
|
+
return
|
|
177
|
+
end = time.time_ns()
|
|
178
|
+
span = self.tracer.start_span(
|
|
179
|
+
name, start_time=end - int(seconds * 1e9), attributes=attributes
|
|
180
|
+
)
|
|
181
|
+
span.end(end_time=end)
|
|
182
|
+
|
|
183
|
+
def _event(self, event: Event) -> None:
|
|
184
|
+
name = self._label(event.function)
|
|
185
|
+
labels = {"function": name}
|
|
186
|
+
if self.tracer is not None and self.spans == "notifications":
|
|
187
|
+
with self.tracer.start_as_current_span("pw." + event.name) as span:
|
|
188
|
+
span.set_attribute("python_wrap.function", name)
|
|
189
|
+
# Exception messages, args, result payloads and context are never labels.
|
|
190
|
+
elif self._current_span is not None and self.spans == "events":
|
|
191
|
+
span = self._current_span()
|
|
192
|
+
if span.is_recording():
|
|
193
|
+
span.add_event("pw." + event.name, {"python_wrap.function": name})
|
|
194
|
+
counter = self._counters.get(event.name)
|
|
195
|
+
if counter is not None:
|
|
196
|
+
counter.add(1, labels)
|
|
197
|
+
fields = event.fields
|
|
198
|
+
if event.name == "rate_limit.waited":
|
|
199
|
+
if self._waits is not None:
|
|
200
|
+
self._waits.record(float(fields["seconds"]), labels)
|
|
201
|
+
if self.wait_spans:
|
|
202
|
+
self._span_back(
|
|
203
|
+
"python_wrap.rate_limit.wait",
|
|
204
|
+
fields.get("seconds"),
|
|
205
|
+
{"python_wrap.function": name},
|
|
206
|
+
)
|
|
207
|
+
if self.attempt_spans and event.name in _ATTEMPT_EVENTS:
|
|
208
|
+
attempt, outcome = _ATTEMPT_EVENTS[event.name](fields)
|
|
209
|
+
self._span_back(
|
|
210
|
+
"python_wrap.retry.attempt",
|
|
211
|
+
fields.get("attempt_seconds"),
|
|
212
|
+
{
|
|
213
|
+
"python_wrap.function": name,
|
|
214
|
+
"python_wrap.retry.attempt": attempt,
|
|
215
|
+
"python_wrap.retry.outcome": outcome,
|
|
216
|
+
},
|
|
217
|
+
)
|
|
218
|
+
|
|
219
|
+
def close(self) -> None:
|
|
220
|
+
if not self.closed:
|
|
221
|
+
self.closed = True
|
|
222
|
+
self._unsubscribe()
|
|
223
|
+
|
|
224
|
+
def __enter__(self) -> Telemetry:
|
|
225
|
+
return self
|
|
226
|
+
|
|
227
|
+
def __exit__(self, *exc: Any) -> None:
|
|
228
|
+
self.close()
|
|
229
|
+
|
|
230
|
+
|
|
231
|
+
_ATTEMPT_EVENTS: dict[str, Any] = {
|
|
232
|
+
"retry.attempt_failed": lambda f: (f.get("attempt", 0), "retry"),
|
|
233
|
+
"retry.gave_up": lambda f: (f.get("attempts", 0), "gave_up"),
|
|
234
|
+
"retry.succeeded": lambda f: (f.get("attempts", 0), "success"),
|
|
235
|
+
}
|
|
236
|
+
|
|
237
|
+
|
|
238
|
+
def enable(
|
|
239
|
+
*,
|
|
240
|
+
tracer_provider: Any = None,
|
|
241
|
+
meter_provider: Any = None,
|
|
242
|
+
max_functions: int = 100,
|
|
243
|
+
spans: str = "events",
|
|
244
|
+
attempt_spans: bool = False,
|
|
245
|
+
wait_spans: bool = False,
|
|
246
|
+
naming: str = "legacy",
|
|
247
|
+
registry: Any = None,
|
|
248
|
+
) -> Telemetry | None:
|
|
249
|
+
"""Subscribe using supplied or global OpenTelemetry providers; no-op if absent.
|
|
250
|
+
|
|
251
|
+
See `Telemetry` for the instruments and span modes. ``naming="otel"`` uses
|
|
252
|
+
OpenTelemetry-style names with units (``python_wrap.retry.gave_up``); the default
|
|
253
|
+
``"legacy"`` keeps the ``pw_*`` names until a minor release changes it. ``registry``
|
|
254
|
+
(default: `python_wrap.health.health`) feeds the component health gauge; pass
|
|
255
|
+
``False`` to leave it out. No provider is installed or shut down by this helper, and
|
|
256
|
+
service attributes come from the provider's resource. Metrics never use
|
|
257
|
+
request/user/cache-key labels; the only label is a bounded ``function``.
|
|
258
|
+
"""
|
|
259
|
+
try:
|
|
260
|
+
from opentelemetry import metrics, trace
|
|
261
|
+
except ImportError:
|
|
262
|
+
return None
|
|
263
|
+
if registry is None:
|
|
264
|
+
from python_wrap.health import health as registry
|
|
265
|
+
tracer = (tracer_provider or trace).get_tracer("python_wrap")
|
|
266
|
+
meter = (meter_provider or metrics).get_meter("python_wrap")
|
|
267
|
+
return Telemetry(
|
|
268
|
+
tracer,
|
|
269
|
+
meter,
|
|
270
|
+
max_functions=max_functions,
|
|
271
|
+
spans=spans,
|
|
272
|
+
attempt_spans=attempt_spans,
|
|
273
|
+
wait_spans=wait_spans,
|
|
274
|
+
naming=naming,
|
|
275
|
+
current_span=trace.get_current_span,
|
|
276
|
+
registry=None if registry is False else registry,
|
|
277
|
+
)
|
|
278
|
+
|
|
279
|
+
|
|
280
|
+
def _safe(value: Any) -> Any:
|
|
281
|
+
"""Scalars pass through; exceptions and other objects become their type name."""
|
|
282
|
+
if value is None or isinstance(value, (bool, int, float, str)):
|
|
283
|
+
return value
|
|
284
|
+
state = getattr(value, "value", None) # enums such as CircuitState
|
|
285
|
+
if isinstance(state, str):
|
|
286
|
+
return state
|
|
287
|
+
return type(value).__name__
|
|
288
|
+
|
|
289
|
+
|
|
290
|
+
_LEVELS = {
|
|
291
|
+
"retry.gave_up": "error",
|
|
292
|
+
"retry.budget_exhausted": "warning",
|
|
293
|
+
"circuit.state_changed": "warning",
|
|
294
|
+
"circuit.rejected": "warning",
|
|
295
|
+
"timeout.expired": "warning",
|
|
296
|
+
"bulkhead.rejected": "warning",
|
|
297
|
+
"rate_limit.rejected": "warning",
|
|
298
|
+
"periodic.failed": "error",
|
|
299
|
+
}
|
|
300
|
+
|
|
301
|
+
|
|
302
|
+
class Breadcrumbs:
|
|
303
|
+
"""Subscription handle returned by `sentry_breadcrumbs`; `close()` stops recording."""
|
|
304
|
+
|
|
305
|
+
def __init__(self, sentry: Any, prefixes: tuple[str, ...]) -> None:
|
|
306
|
+
self.sentry, self.prefixes = sentry, prefixes
|
|
307
|
+
self._unsubscribe = subscribe(self._event)
|
|
308
|
+
self.closed = False
|
|
309
|
+
|
|
310
|
+
def _event(self, event: Event) -> None:
|
|
311
|
+
if not event.name.startswith(self.prefixes):
|
|
312
|
+
return
|
|
313
|
+
data = {key: _safe(value) for key, value in event.fields.items()}
|
|
314
|
+
data["function"] = event.function
|
|
315
|
+
self.sentry.add_breadcrumb(
|
|
316
|
+
category="python_wrap",
|
|
317
|
+
message=f"{event.name} {event.function}",
|
|
318
|
+
level=_LEVELS.get(event.name, "info"),
|
|
319
|
+
data=data,
|
|
320
|
+
)
|
|
321
|
+
|
|
322
|
+
def close(self) -> None:
|
|
323
|
+
if not self.closed:
|
|
324
|
+
self.closed = True
|
|
325
|
+
self._unsubscribe()
|
|
326
|
+
|
|
327
|
+
def __enter__(self) -> Breadcrumbs:
|
|
328
|
+
return self
|
|
329
|
+
|
|
330
|
+
def __exit__(self, *exc: Any) -> None:
|
|
331
|
+
self.close()
|
|
332
|
+
|
|
333
|
+
|
|
334
|
+
def sentry_breadcrumbs(
|
|
335
|
+
*,
|
|
336
|
+
sentry: Any = None,
|
|
337
|
+
prefixes: tuple[str, ...] = ("retry.", "circuit.", "timeout.", "bulkhead.", "rate_limit."),
|
|
338
|
+
) -> Breadcrumbs | None:
|
|
339
|
+
"""Record python-wrap events as Sentry breadcrumbs, so an error report shows its retries.
|
|
340
|
+
|
|
341
|
+
Each event becomes a breadcrumb in category ``python_wrap`` (gave-up and failed
|
|
342
|
+
periodic runs at level ``error``, rejections and timeouts at ``warning``). Exception
|
|
343
|
+
fields are reduced to type names; messages, arguments and results are never sent.
|
|
344
|
+
|
|
345
|
+
Args:
|
|
346
|
+
sentry: The ``sentry_sdk`` module or any object with ``add_breadcrumb``; by
|
|
347
|
+
default ``sentry_sdk`` is imported if installed.
|
|
348
|
+
prefixes: Event name prefixes to record.
|
|
349
|
+
|
|
350
|
+
Returns:
|
|
351
|
+
A `Breadcrumbs` handle, or None when ``sentry_sdk`` is not installed.
|
|
352
|
+
"""
|
|
353
|
+
if sentry is None:
|
|
354
|
+
try:
|
|
355
|
+
import importlib
|
|
356
|
+
|
|
357
|
+
sentry = importlib.import_module("sentry_sdk")
|
|
358
|
+
except ImportError:
|
|
359
|
+
return None
|
|
360
|
+
return Breadcrumbs(sentry, prefixes)
|
|
361
|
+
|
|
362
|
+
|
|
363
|
+
def annotate_span(span: Any, exc: BaseException) -> None:
|
|
364
|
+
"""Add a re-raised exception's retry timeline to an OpenTelemetry-style span.
|
|
365
|
+
|
|
366
|
+
Sets ``python_wrap.attempts`` and, per attempt ``n``, ``python_wrap.attempt.<n>.exception``
|
|
367
|
+
and ``.duration``; adds one ``python_wrap.retry`` span event per attempt. Does nothing
|
|
368
|
+
for exceptions that did not come out of `retry`.
|
|
369
|
+
|
|
370
|
+
Args:
|
|
371
|
+
span: An object with ``set_attribute`` (and optionally ``add_event``).
|
|
372
|
+
exc: The exception being recorded.
|
|
373
|
+
"""
|
|
374
|
+
from python_wrap.retry import attempt_history
|
|
375
|
+
|
|
376
|
+
history = attempt_history(exc)
|
|
377
|
+
if not history:
|
|
378
|
+
return
|
|
379
|
+
span.set_attribute("python_wrap.attempts", len(history))
|
|
380
|
+
add_event = getattr(span, "add_event", None)
|
|
381
|
+
for record in history:
|
|
382
|
+
prefix = f"python_wrap.attempt.{record.number}"
|
|
383
|
+
span.set_attribute(prefix + ".exception", record.exception)
|
|
384
|
+
span.set_attribute(prefix + ".duration", record.duration)
|
|
385
|
+
if add_event is not None:
|
|
386
|
+
attributes: dict[str, Any] = {
|
|
387
|
+
"attempt": record.number,
|
|
388
|
+
"exception": record.exception,
|
|
389
|
+
"duration": record.duration,
|
|
390
|
+
}
|
|
391
|
+
if record.next_delay is not None:
|
|
392
|
+
attributes["next_delay"] = record.next_delay
|
|
393
|
+
add_event("python_wrap.retry", attributes)
|
|
394
|
+
|
|
395
|
+
|
|
396
|
+
def genai_span_attributes(event: Event) -> dict[str, Any]:
|
|
397
|
+
"""OpenTelemetry GenAI semantic-convention attributes for a ``genai.*`` event.
|
|
398
|
+
|
|
399
|
+
Maps ``gen_ai.operation.name`` (``chat`` or ``execute_tool``), ``gen_ai.system``,
|
|
400
|
+
``gen_ai.request.model``, ``gen_ai.usage.input_tokens``/``output_tokens`` and
|
|
401
|
+
``gen_ai.tool.name``; python-wrap extras (run id, step, cost, latency, attempts) use the
|
|
402
|
+
``python_wrap.`` prefix. Captured content, when present, becomes JSON strings under
|
|
403
|
+
``gen_ai.input.messages`` / ``gen_ai.output.messages``. ``None`` values are omitted.
|
|
404
|
+
"""
|
|
405
|
+
import json
|
|
406
|
+
|
|
407
|
+
fields = event.fields
|
|
408
|
+
is_tool = event.name == "genai.tool_call"
|
|
409
|
+
raw: dict[str, Any] = {
|
|
410
|
+
"gen_ai.operation.name": "execute_tool" if is_tool else "chat",
|
|
411
|
+
"gen_ai.system": fields.get("system"),
|
|
412
|
+
"gen_ai.request.model": fields.get("model"),
|
|
413
|
+
"gen_ai.usage.input_tokens": fields.get("input_tokens"),
|
|
414
|
+
"gen_ai.usage.output_tokens": fields.get("output_tokens"),
|
|
415
|
+
"gen_ai.tool.name": fields.get("tool") if is_tool else None,
|
|
416
|
+
"python_wrap.run_id": fields.get("run_id"),
|
|
417
|
+
"python_wrap.step": fields.get("step"),
|
|
418
|
+
"python_wrap.cost": fields.get("cost"),
|
|
419
|
+
"python_wrap.latency": fields.get("latency"),
|
|
420
|
+
"python_wrap.attempts": fields.get("attempts"),
|
|
421
|
+
"error.type": fields.get("error_type"),
|
|
422
|
+
}
|
|
423
|
+
for key, target in (("input", "gen_ai.input.messages"), ("output", "gen_ai.output.messages")):
|
|
424
|
+
if fields.get(key) is not None:
|
|
425
|
+
raw[target] = json.dumps(fields[key], default=str)
|
|
426
|
+
return {key: value for key, value in raw.items() if value is not None}
|
|
427
|
+
|
|
428
|
+
|
|
429
|
+
class GenAITelemetry:
|
|
430
|
+
"""Subscription that turns ``genai.*`` events into OpenTelemetry spans."""
|
|
431
|
+
|
|
432
|
+
def __init__(self, tracer: Any) -> None:
|
|
433
|
+
self.tracer = tracer
|
|
434
|
+
self._unsubscribe = subscribe(self._event)
|
|
435
|
+
self.closed = False
|
|
436
|
+
|
|
437
|
+
def _event(self, event: Event) -> None:
|
|
438
|
+
if event.name not in ("genai.llm_call", "genai.tool_call"):
|
|
439
|
+
return
|
|
440
|
+
fields = event.fields
|
|
441
|
+
attributes = genai_span_attributes(event)
|
|
442
|
+
if event.name == "genai.tool_call":
|
|
443
|
+
name = f"execute_tool {fields.get('tool') or event.function}"
|
|
444
|
+
else:
|
|
445
|
+
name = f"chat {fields.get('model') or event.function}"
|
|
446
|
+
started = float(fields.get("started") or 0.0)
|
|
447
|
+
latency = float(fields.get("latency") or 0.0)
|
|
448
|
+
span = self.tracer.start_span(name, start_time=int(started * 1e9))
|
|
449
|
+
try:
|
|
450
|
+
for key, value in attributes.items():
|
|
451
|
+
span.set_attribute(key, value)
|
|
452
|
+
finally:
|
|
453
|
+
span.end(end_time=int((started + latency) * 1e9))
|
|
454
|
+
|
|
455
|
+
def close(self) -> None:
|
|
456
|
+
if not self.closed:
|
|
457
|
+
self.closed = True
|
|
458
|
+
self._unsubscribe()
|
|
459
|
+
|
|
460
|
+
def __enter__(self) -> GenAITelemetry:
|
|
461
|
+
return self
|
|
462
|
+
|
|
463
|
+
def __exit__(self, *exc: Any) -> None:
|
|
464
|
+
self.close()
|
|
465
|
+
|
|
466
|
+
|
|
467
|
+
def enable_genai(*, tracer: Any = None, tracer_provider: Any = None) -> GenAITelemetry | None:
|
|
468
|
+
"""Emit GenAI-convention spans for traced LLM and tool calls; no-op without OpenTelemetry.
|
|
469
|
+
|
|
470
|
+
Args:
|
|
471
|
+
tracer: A tracer to use directly (no OpenTelemetry import needed).
|
|
472
|
+
tracer_provider: Provider to take the tracer from instead of the global one.
|
|
473
|
+
|
|
474
|
+
Returns:
|
|
475
|
+
A closable `GenAITelemetry`, or None when no tracer was given and
|
|
476
|
+
``opentelemetry`` is not installed.
|
|
477
|
+
"""
|
|
478
|
+
if tracer is None:
|
|
479
|
+
try:
|
|
480
|
+
from opentelemetry import trace
|
|
481
|
+
except ImportError:
|
|
482
|
+
return None
|
|
483
|
+
tracer = (tracer_provider or trace).get_tracer("python_wrap")
|
|
484
|
+
return GenAITelemetry(tracer)
|
python_wrap/periodic.py
CHANGED
|
@@ -31,7 +31,7 @@ import time
|
|
|
31
31
|
from collections.abc import AsyncIterator, Callable, Coroutine, Iterator
|
|
32
32
|
from typing import Any, Generic, Literal, ParamSpec, Protocol, TypeVar, overload
|
|
33
33
|
|
|
34
|
-
from python_wrap import _core
|
|
34
|
+
from python_wrap import _core, _fork
|
|
35
35
|
from python_wrap._core import LoggerLike
|
|
36
36
|
|
|
37
37
|
__all__ = ["AsyncPeriodic", "Periodic", "periodic"]
|
|
@@ -88,7 +88,7 @@ class _Base(Generic[P, R]):
|
|
|
88
88
|
self._runs = 0
|
|
89
89
|
self._last_error: BaseException | None = None
|
|
90
90
|
self._pending: BaseException | None = None # on_error="raise", surfaced by stop()
|
|
91
|
-
self._lock =
|
|
91
|
+
self._lock = _fork.ForkSafeLock()
|
|
92
92
|
functools.update_wrapper(self, func) # type: ignore[arg-type]
|
|
93
93
|
|
|
94
94
|
def __reduce__(self) -> str:
|
|
@@ -163,6 +163,15 @@ class Periodic(_Base[P, R]):
|
|
|
163
163
|
super().__init__(func, *config)
|
|
164
164
|
self._stop_event = threading.Event()
|
|
165
165
|
self._thread: threading.Thread | None = None
|
|
166
|
+
self._fork_warning = False
|
|
167
|
+
_fork.register(self)
|
|
168
|
+
|
|
169
|
+
def _reset_after_fork(self) -> None:
|
|
170
|
+
self._fork_warning = self._thread is not None
|
|
171
|
+
self._thread = None
|
|
172
|
+
self._stop_event = threading.Event()
|
|
173
|
+
self._runs = 0
|
|
174
|
+
self._last_error = self._pending = None
|
|
166
175
|
|
|
167
176
|
def __call__(self, *args: P.args, **kwargs: P.kwargs) -> R:
|
|
168
177
|
return self._func(*args, **kwargs) # type: ignore[no-any-return]
|
|
@@ -170,6 +179,12 @@ class Periodic(_Base[P, R]):
|
|
|
170
179
|
@property
|
|
171
180
|
def running(self) -> bool:
|
|
172
181
|
"""True while the background thread is alive."""
|
|
182
|
+
if self._fork_warning:
|
|
183
|
+
self._fork_warning = False
|
|
184
|
+
_core.get_logger(self._logger).warning(
|
|
185
|
+
"periodic %s: inherited loop stopped after fork; call start() in this worker",
|
|
186
|
+
self._name,
|
|
187
|
+
)
|
|
173
188
|
thread = self._thread
|
|
174
189
|
return thread is not None and thread.is_alive()
|
|
175
190
|
|
|
@@ -274,10 +289,17 @@ class AsyncPeriodic(_Base[P, R]):
|
|
|
274
289
|
super().__init__(func, *config)
|
|
275
290
|
self._task: asyncio.Task[None] | None = None
|
|
276
291
|
self._stopping = False
|
|
292
|
+
_fork.register(self)
|
|
277
293
|
mark = getattr(inspect, "markcoroutinefunction", None) # Python 3.12+
|
|
278
294
|
if mark is not None:
|
|
279
295
|
mark(self)
|
|
280
296
|
|
|
297
|
+
def _reset_after_fork(self) -> None:
|
|
298
|
+
self._task = None
|
|
299
|
+
self._stopping = True
|
|
300
|
+
self._runs = 0
|
|
301
|
+
self._last_error = self._pending = None
|
|
302
|
+
|
|
281
303
|
def __call__(self, *args: P.args, **kwargs: P.kwargs) -> Coroutine[Any, Any, R]:
|
|
282
304
|
return self._func(*args, **kwargs) # type: ignore[no-any-return]
|
|
283
305
|
|