trodo-python 3.0.7__py3-none-any.whl → 3.1.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.
trodo/_version.py CHANGED
@@ -1 +1 @@
1
- SDK_VERSION = "3.0.7"
1
+ SDK_VERSION = "3.1.0"
trodo/delivery/sender.py CHANGED
@@ -34,7 +34,12 @@ and PostHog have converged on (1 Oct 2026 survey):
34
34
  hundreds of traces in its last seconds. At exit the sender opens as many
35
35
  requests again as ``max_in_flight`` (3.0.5): ordinary requests sent just
36
36
  before the exit can take seconds each, and the hand-off must not wait
37
- behind them.
37
+ behind them. The exit hand-off does not wait out a 429 pause: the server
38
+ holds an exiting batch whatever the rate, and says so if it cannot.
39
+ - lifecycle (``_phase``, changed only in ``_to``): open → exiting (atexit) or
40
+ closing (``shutdown``) → stopped. ``atexit`` runs once, at the real exit,
41
+ so unlike Node's beforeExit nothing reopens it. Idle, armed, sending and
42
+ paused are read off the queue, requests and pause (``_state_locked``).
38
43
  - the server holds over-rate items itself (202 ``queued``) and stores them
39
44
  at the team's rate; the sender says so on stderr once per 10 minutes.
40
45
  - ``immediate`` mode for platforms that freeze between requests (Lambda,
@@ -70,6 +75,16 @@ _MIN_BACKOFF_S = 1.0
70
75
  _MAX_BACKOFF_S = 60.0
71
76
  _TRANSIENT = {408, 425, 429, 500, 502, 503, 504}
72
77
 
78
+ # Lifecycle (same names as the Node sender). "exiting": the atexit flush;
79
+ # "closing": shutdown's. Node also has exiting -> open, for a beforeExit in a
80
+ # process that keeps running; atexit is final.
81
+ _TRANSITIONS = {
82
+ "open": ("exiting", "closing"),
83
+ "exiting": ("closing",),
84
+ "closing": ("stopped",),
85
+ "stopped": (),
86
+ }
87
+
73
88
 
74
89
  def detect_mode(env: Optional[Dict[str, str]] = None) -> str:
75
90
  """'immediate' on serverless / freeze-between-requests platforms, else 'background'."""
@@ -135,7 +150,8 @@ class Sender:
135
150
  self._wake = threading.Condition(self._lock)
136
151
  self._paused_until: Optional[float] = None
137
152
  self._not_before: float = 0.0 # backoff after a failed batch
138
- self._stopped = False
153
+ self._phase = "open"
154
+ self._warned_after_shutdown = False
139
155
  self._flush_requested = False
140
156
  self._in_flight = 0 # requests
141
157
  self._in_flight_items = 0
@@ -146,9 +162,9 @@ class Sender:
146
162
  self._unit_cap: Optional[int] = None # the team's ceiling, once a 429 names it
147
163
  self._last_rate: Optional[Dict[str, Any]] = None
148
164
  self._warned_paced_at = 0.0
149
- self._exiting = False # set by the exit flush and shutdown: the server holds the batch
150
165
  self._threads: List[threading.Thread] = []
151
166
  self._runs_in_flight: Dict[str, int] = {} # run_id -> requests carrying it
167
+ self._exit_drains: List[Callable[[], None]] = [] # producers that hand their buffers over before an exit flush
152
168
  if self.mode == "background" and register_atexit:
153
169
  atexit.register(self._atexit)
154
170
 
@@ -157,7 +173,8 @@ class Sender:
157
173
  def enqueue(self, item: Item) -> None:
158
174
  """Queue an item. Returns at once in background mode; in immediate mode
159
175
  returns once the item is sent (or given up on)."""
160
- if self._stopped:
176
+ if self._phase == "stopped":
177
+ self._drop_after_shutdown()
161
178
  return
162
179
  if self.mode == "immediate":
163
180
  self._send_immediate(item)
@@ -176,8 +193,20 @@ class Sender:
176
193
  if shed:
177
194
  self._drop_queue_full(shed)
178
195
 
196
+ def add_exit_drain(self, fn: Callable[[], None]) -> None:
197
+ """Register a producer (the span processor) whose buffer is handed over before an exit flush."""
198
+ self._exit_drains.append(fn)
199
+
200
+ def _drain_producers(self) -> None:
201
+ for fn in list(self._exit_drains):
202
+ try:
203
+ fn()
204
+ except Exception:
205
+ pass
206
+
179
207
  def flush(self, timeout_s: Optional[float] = None) -> None:
180
- """Send everything queued and wait for it, for at most ``timeout_s``."""
208
+ """Send everything queued and wait for it, for at most ``timeout_s``.
209
+ A backoff is skipped; a 429 pause is waited out, within the bound."""
181
210
  if self.mode == "immediate":
182
211
  return
183
212
  deadline = None if timeout_s is None else self._now() + timeout_s
@@ -186,7 +215,7 @@ class Sender:
186
215
  self._flush_requested = True
187
216
  self._ensure_thread_locked()
188
217
  self._wake.notify_all()
189
- while (self._queue or self._in_flight) and not self._stopped:
218
+ while (self._queue or self._in_flight) and self._phase != "stopped":
190
219
  remaining = None if deadline is None else deadline - self._now()
191
220
  if remaining is not None and remaining <= 0:
192
221
  break
@@ -194,10 +223,14 @@ class Sender:
194
223
  self._flush_requested = False
195
224
 
196
225
  def shutdown(self, timeout_s: Optional[float] = None) -> None:
197
- self._exiting = True
226
+ if self._phase == "open":
227
+ self._drain_producers()
228
+ with self._lock:
229
+ if not self._to_locked("closing"):
230
+ return # already stopped (or stopping)
198
231
  self.flush(self._o["exit_flush_s"] if timeout_s is None else timeout_s)
199
232
  with self._lock:
200
- self._stopped = True
233
+ self._to_locked("stopped")
201
234
  left = len(self._queue)
202
235
  spans_left = sum(_units_of(q.item) for q in self._queue)
203
236
  self._queue.clear()
@@ -210,18 +243,57 @@ class Sender:
210
243
  def stats(self) -> Dict[str, Any]:
211
244
  with self._lock:
212
245
  return {
213
- "queued": len(self._queue), "queued_bytes": self._queue_bytes, "in_flight": self._in_flight,
246
+ "state": self._state_locked(), "queued": len(self._queue), "queued_bytes": self._queue_bytes, "in_flight": self._in_flight,
214
247
  "sent": self._stats["sent"], "dropped": self._stats["dropped"],
215
248
  "dropped_by_reason": dict(self._stats["dropped_by_reason"]),
216
249
  "paused_until": self._paused_until, "mode": self.mode,
217
250
  }
218
251
 
252
+ # ── lifecycle ─────────────────────────────────────────────────────────────
253
+
254
+ def _to_locked(self, nxt: str) -> bool:
255
+ """The one place the phase changes (lock held). False for a move the table does not allow."""
256
+ if nxt not in _TRANSITIONS[self._phase]:
257
+ return False
258
+ self._phase = nxt
259
+ if nxt in ("exiting", "closing"):
260
+ # The exit hand-off is held by the server whatever the rate: it does not wait out a pause.
261
+ self._paused_until = None
262
+ self._not_before = 0.0
263
+ self._wake.notify_all()
264
+ return True
265
+
266
+ def _exiting_locked(self) -> bool:
267
+ return self._phase in ("exiting", "closing")
268
+
269
+ def _state_locked(self) -> str:
270
+ if self._phase == "stopped":
271
+ return "stopped"
272
+ if self._phase != "open":
273
+ return "exiting"
274
+ if self._paused_until is not None and self._paused_until > self._now():
275
+ return "paused"
276
+ if self._in_flight:
277
+ return "sending"
278
+ return "armed" if self._queue else "idle"
279
+
280
+ def _drop_after_shutdown(self) -> None:
281
+ """Enqueued after shutdown: counted, said once in debug, never sent."""
282
+ with self._lock:
283
+ self._stats["dropped"] += 1
284
+ by = self._stats["dropped_by_reason"]
285
+ by["after_shutdown"] = by.get("after_shutdown", 0) + 1
286
+ warned = self._warned_after_shutdown
287
+ self._warned_after_shutdown = True
288
+ if not warned:
289
+ self._log("an item was enqueued after shutdown and dropped; stats()['dropped_by_reason']['after_shutdown'] counts them")
290
+
219
291
  # ── background thread ─────────────────────────────────────────────────────
220
292
 
221
293
  def _ensure_thread_locked(self) -> None:
222
294
  self._threads = [t for t in self._threads if t.is_alive()]
223
295
  slots = max(1, int(self._o["max_in_flight"]))
224
- if self._exiting:
296
+ if self._exiting_locked():
225
297
  slots *= 2 # the hand-off goes out beside requests still in flight
226
298
  while len(self._threads) < slots:
227
299
  t = threading.Thread(target=self._run, name=f"trodo-sender-{len(self._threads) + 1}", daemon=True)
@@ -233,7 +305,7 @@ class Sender:
233
305
  while True:
234
306
  with self._lock:
235
307
  while True:
236
- if self._stopped:
308
+ if self._phase == "stopped":
237
309
  return
238
310
  if not self._queue:
239
311
  self._wake.wait(timeout=interval)
@@ -490,9 +562,9 @@ class Sender:
490
562
 
491
563
  def _envelope(self, batch: List[_Queued]) -> Dict[str, Any]:
492
564
  env: Dict[str, Any] = {"items": [q.item for q in batch]}
493
- if self._exiting:
494
- env["exiting"] = True
495
565
  with self._lock:
566
+ if self._exiting_locked():
567
+ env["exiting"] = True
496
568
  if self._unreported["count"]:
497
569
  env["dropped"] = {"count": self._unreported["count"], "by_reason": dict(self._unreported["by_reason"])}
498
570
  return env
@@ -582,7 +654,12 @@ class Sender:
582
654
  self._sleep(wait)
583
655
 
584
656
  def _atexit(self) -> None:
585
- self._exiting = True
657
+ if self._phase == "open":
658
+ self._drain_producers()
659
+ with self._lock:
660
+ if self._phase != "open" or not (self._queue or self._in_flight_items):
661
+ return # stopped already, or nothing to hand over
662
+ self._to_locked("exiting")
586
663
  try:
587
664
  self.flush(self._o["exit_flush_s"])
588
665
  except Exception:
trodo/otel/processor.py CHANGED
@@ -8,12 +8,22 @@ flush asynchronously via append_spans.
8
8
  from __future__ import annotations
9
9
 
10
10
  import threading
11
+ import time
12
+ from collections import OrderedDict
11
13
  from dataclasses import dataclass, asdict
12
14
  import json
13
- from typing import Any, Dict, List, Optional, Union
15
+ from typing import Any, Callable, Dict, List, Optional, Union
14
16
 
15
17
  # How long end_run waits for the run's queued spans to send before sending the end.
16
18
  END_RUN_FLUSH_S = 5.0
19
+ # A run's buffers are forgotten after this long without a span, or once more
20
+ # than MAX_TRACKED_RUNS runs are held (least recently active first): spans of
21
+ # a run that never finalises (OTel spans outside wrap_agent, a start_run with
22
+ # no end_run) used to be held for the life of the process. Its unsent spans
23
+ # are sent ahead; only the totals the final ingest would carry are lost, and
24
+ # the server keeps the larger of its own and ours. Same rule as the Node SDK.
25
+ RUN_IDLE_S = 3600.0
26
+ MAX_TRACKED_RUNS = 10_000
17
27
 
18
28
 
19
29
  @dataclass
@@ -156,6 +166,9 @@ class TrodoSpanProcessor:
156
166
  flush_interval_s: float = 5.0,
157
167
  max_spans_per_run: int = 1000,
158
168
  sender: Any = None,
169
+ run_idle_s: float = RUN_IDLE_S,
170
+ max_tracked_runs: int = MAX_TRACKED_RUNS,
171
+ now: Callable[[], float] = time.time,
159
172
  ) -> None:
160
173
  self._http = http_client
161
174
  # The background sender (2.24). Without one, sends block as before 2.24.
@@ -172,19 +185,72 @@ class TrodoSpanProcessor:
172
185
  self._shutdown = False
173
186
  # run_ids that are "joined" (owned by a remote service) — their spans
174
187
  # are flushed incrementally via append_spans, never batched for a
175
- # local ingest_run call.
176
- self._joined_runs: set[str] = set()
188
+ # local ingest_run call. Counted: two joins of one run (start_run and
189
+ # join_run, or two join_runs at once) keep it joined until the last ends.
190
+ self._joined_runs: Dict[str, int] = {}
191
+ # run_id -> last span (or join), oldest first: what eviction reads.
192
+ self._active: "OrderedDict[str, float]" = OrderedDict()
193
+ self._run_idle_s = run_idle_s
194
+ self._max_tracked_runs = max_tracked_runs
195
+ self._now = now
196
+ # Spans still buffered here go in the sender's exit flush (as flush() does).
197
+ if sender is not None and hasattr(sender, "add_exit_drain"):
198
+ sender.add_exit_drain(self.force_flush)
177
199
 
178
200
  def mark_joined(self, run_id: str) -> None:
179
201
  with self._lock:
180
- self._joined_runs.add(run_id)
202
+ self._joined_runs[run_id] = self._joined_runs.get(run_id, 0) + 1
203
+ evicted = self._touch_locked(run_id)
204
+ self._send_evicted(evicted)
181
205
 
182
206
  def unmark_joined(self, run_id: str) -> None:
207
+ """One join of the run ended; it stops being joined when the last one does."""
183
208
  with self._lock:
184
- self._joined_runs.discard(run_id)
185
- self._pending.pop(run_id, None)
186
- self._sent_ahead.pop(run_id, None)
187
- self._bucket_bytes.pop(run_id, None)
209
+ left = self._joined_runs.get(run_id, 0) - 1
210
+ if left > 0:
211
+ self._joined_runs[run_id] = left
212
+ else:
213
+ self._forget_locked(run_id)
214
+
215
+ def tracked_runs(self) -> int:
216
+ """How many runs hold buffers here (for tests and debugging)."""
217
+ with self._lock:
218
+ return len(self._active)
219
+
220
+ def _forget_locked(self, run_id: str) -> List[TrodoSpan]:
221
+ """Drop everything held for a run (finalised, ended, or evicted); returns its unsent spans."""
222
+ self._joined_runs.pop(run_id, None)
223
+ self._sent_ahead.pop(run_id, None)
224
+ self._bucket_bytes.pop(run_id, None)
225
+ self._active.pop(run_id, None)
226
+ return self._pending.pop(run_id, None) or []
227
+
228
+ def _release_locked(self, run_id: str) -> List[TrodoSpan]:
229
+ """A run finalised or ended: drop its buffers (returns unsent spans); a join still open keeps routing."""
230
+ self._sent_ahead.pop(run_id, None)
231
+ self._bucket_bytes.pop(run_id, None)
232
+ if run_id not in self._joined_runs:
233
+ self._active.pop(run_id, None)
234
+ return self._pending.pop(run_id, None) or []
235
+
236
+ def _touch_locked(self, run_id: str) -> List[tuple]:
237
+ """Note activity on a run, then evict the idle ones and any over the cap.
238
+ Returns (run_id, unsent spans) of the evicted, for the caller to send ahead."""
239
+ t = self._now()
240
+ self._active.pop(run_id, None)
241
+ self._active[run_id] = t
242
+ evicted: List[tuple] = []
243
+ while self._active:
244
+ rid, at = next(iter(self._active.items()))
245
+ if len(self._active) <= self._max_tracked_runs and t - at <= self._run_idle_s:
246
+ break
247
+ evicted.append((rid, self._forget_locked(rid)))
248
+ return evicted
249
+
250
+ def _send_evicted(self, evicted: List[tuple]) -> None:
251
+ for rid, spans in evicted:
252
+ for piece in _pieces([x.to_dict() for x in spans]):
253
+ self._send_spans(rid, piece)
188
254
 
189
255
  def enqueue_span(self, span: TrodoSpan) -> None:
190
256
  """Buffer a completed span under its run_id.
@@ -195,6 +261,7 @@ class TrodoSpanProcessor:
195
261
  d = span.to_dict()
196
262
  n = _size(d)
197
263
  with self._lock:
264
+ evicted = self._touch_locked(span.run_id)
198
265
  joined = span.run_id in self._joined_runs
199
266
  if not joined:
200
267
  bucket = self._pending.setdefault(span.run_id, [])
@@ -215,6 +282,7 @@ class TrodoSpanProcessor:
215
282
  self._bucket_bytes[span.run_id] = held
216
283
  if chunk:
217
284
  self._sent_ahead.setdefault(span.run_id, []).extend(_SentSpan(x) for x in chunk)
285
+ self._send_evicted(evicted)
218
286
  if joined:
219
287
  self._send_spans(span.run_id, [d])
220
288
  elif chunk:
@@ -238,9 +306,7 @@ class TrodoSpanProcessor:
238
306
  def ingest_run(self, run: TrodoRun) -> None:
239
307
  """Flush a run + all its buffered spans in one call."""
240
308
  with self._lock:
241
- spans = self._pending.pop(run.run_id, [])
242
- self._sent_ahead.pop(run.run_id, None)
243
- self._bucket_bytes.pop(run.run_id, None)
309
+ spans = self._release_locked(run.run_id)
244
310
  payload: Dict[str, Any] = {"run": run.to_dict()}
245
311
  if spans:
246
312
  # All but the last piece go ahead; the run travels with the last.
@@ -278,9 +344,7 @@ class TrodoSpanProcessor:
278
344
  """
279
345
  try:
280
346
  with self._lock:
281
- buffered = self._pending.pop(run_id, None) or []
282
- self._sent_ahead.pop(run_id, None)
283
- self._bucket_bytes.pop(run_id, None)
347
+ buffered = self._release_locked(run_id)
284
348
  for piece in _pieces([s.to_dict() for s in buffered]):
285
349
  self._send_spans(run_id, piece)
286
350
  if self._sender is not None:
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: trodo-python
3
- Version: 3.0.7
3
+ Version: 3.1.0
4
4
  Summary: Trodo Analytics SDK for Python — server-side event tracking
5
5
  License: ISC
6
6
  Keywords: analytics,tracking,trodo,server-side
@@ -1,5 +1,5 @@
1
1
  trodo/__init__.py,sha256=tG--Ls4hitU3XD4Krnt5eP-sIQRrfCZJsnmHyrXArtY,27509
2
- trodo/_version.py,sha256=HaPbjJlhd6w5uTeEH8wthq8a82UENc6cc_BVaSTa_Ao,22
2
+ trodo/_version.py,sha256=6900FzmjpMm15vbOxHMGhVkTqXfdTjIrIcRw99BqYwA,22
3
3
  trodo/client.py,sha256=I6SRllM6LbEj4XPoT8UD47lRglI7jhKxgOdYKYs_x-c,23880
4
4
  trodo/types.py,sha256=eySgUvCXROG2TxtxgiU0MNr5iH0DEcduK8bmYtTKG44,3138
5
5
  trodo/user_context.py,sha256=uHCI2WYoOI3cNwdIUEuZdX4VYSu14pzm348ksn6hn_c,8195
@@ -12,7 +12,7 @@ trodo/api/management.py,sha256=uwhr0ZI1pvguz5-itW1KcgRj0TXM2n4KDa-hGIaBdTA,4023
12
12
  trodo/auto/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
13
13
  trodo/auto/auto_event_manager.py,sha256=cztuRsRkNoJE5R4NfSfTrTJTGl4jx2Yb-Ncy0aVAPo8,4247
14
14
  trodo/delivery/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
15
- trodo/delivery/sender.py,sha256=skmmbNWQ20GxmLk4VmkZdWGQDnk7cc3bGso7X3O15Ko,29598
15
+ trodo/delivery/sender.py,sha256=sDLc2tNc80dYUCkTuay-pjSMktHvebbyh8kvc_8AIsE,33211
16
16
  trodo/managers/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
17
17
  trodo/managers/dataset_manager.py,sha256=HTFszK-wKmwjW-aw7xJWr5EKvDpJ_om496MLDr3gelg,13920
18
18
  trodo/managers/group_manager.py,sha256=ki3Se3qEoSZfREX63oeDeBmEfZF-ISHLE8azEtLg0tM,3542
@@ -23,7 +23,7 @@ trodo/otel/__init__.py,sha256=yiRFXWUU45bAM2CV37XeO7zf1hmnmjufdP4XO50yEyE,624
23
23
  trodo/otel/auto_instrument.py,sha256=WzSrocREeyNcykZ-0mzVuYoI_zn5QWDQZkUwDK__kFU,29103
24
24
  trodo/otel/context.py,sha256=Jd0aTc0Q-1dM5kXXinhZD8YtnpdKgvneNiODyboVGKY,1418
25
25
  trodo/otel/helpers.py,sha256=XOMWcgZHaq5SQbkFxDaXPE4CDFjn01xjJmJ1vIxvwpw,20730
26
- trodo/otel/processor.py,sha256=ezaesBaxgv4-Mx8aHyp3ur41rvHwnQnjCNlPTe8rhjU,12343
26
+ trodo/otel/processor.py,sha256=hMX-gHpgzk36_lDVsV7pcQOG6YPIhA3hFOuhNPqrbNQ,15528
27
27
  trodo/otel/prompt_trace.py,sha256=VMsTynTXA2W8x6Vg0VVlO2Ta3tTbU3Lw2MNjye6ufs0,17328
28
28
  trodo/otel/register.py,sha256=7X3AfFQ5YvHGOUmdq8J38LQGvOJFPD907yT3uAp90lI,9607
29
29
  trodo/otel/transport.py,sha256=hzZz8gwSMGJ8CxdijmLn1Ljt18owr9XTWy13DLbwYbw,2441
@@ -40,7 +40,7 @@ trodo/session/server_session.py,sha256=McsudEiq33XDq3nqxgzBcUvIjQxCMscwEuAPnYXrT
40
40
  trodo/session/session_manager.py,sha256=7ht5LeeZX1HLLfPeNV_a8NkXGbHl3up0CRtCGr3EzjQ,2995
41
41
  trodo/util/__init__.py,sha256=Z9c4rPPdKg06Kk3byKheDqksSgR4WNvS475oQ5sNljc,54
42
42
  trodo/util/lru.py,sha256=QIsM7s6J_E9ZjiXatSyReZIEeGypTAcgrPWWy8YsRa4,2465
43
- trodo_python-3.0.7.dist-info/METADATA,sha256=GhQVI_bCmx4uBv77JfXY66uLrrFUXHCkKlDEJnw_Soc,25307
44
- trodo_python-3.0.7.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
45
- trodo_python-3.0.7.dist-info/top_level.txt,sha256=VCQu1CJWFmNsqTs1YxMcw4Mq35Tc3z3uI9RwHEXAayQ,6
46
- trodo_python-3.0.7.dist-info/RECORD,,
43
+ trodo_python-3.1.0.dist-info/METADATA,sha256=bjJjxdZswxzjLUrOu4IIgYB3N85bzZ6JYxTdNfdzxPE,25307
44
+ trodo_python-3.1.0.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
45
+ trodo_python-3.1.0.dist-info/top_level.txt,sha256=VCQu1CJWFmNsqTs1YxMcw4Mq35Tc3z3uI9RwHEXAayQ,6
46
+ trodo_python-3.1.0.dist-info/RECORD,,