trodo-python 3.0.6__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/__init__.py CHANGED
@@ -339,6 +339,7 @@ def get_prompt(
339
339
  cache_ttl_seconds: Optional[float] = None,
340
340
  fallback: Optional[Dict[str, Any]] = None,
341
341
  max_retries: int = 2,
342
+ record_variables: bool = False,
342
343
  ) -> ManagedPrompt:
343
344
  """Fetch a managed prompt by name.
344
345
 
@@ -357,6 +358,10 @@ def get_prompt(
357
358
  compiled = p.compile(q="where is my order")
358
359
  # compiled.messages / compiled.model / compiled.tools
359
360
 
361
+ ``record_variables=True`` records the compiled values on the span
362
+ (``trodo.prompt.variables``) so the Playground can replay the exact call.
363
+ Off by default: values are often user data.
364
+
360
365
  :raises LookupError: if the prompt cannot be fetched and nothing is cached
361
366
  and no ``fallback`` was given
362
367
  """
@@ -367,6 +372,7 @@ def get_prompt(
367
372
  cache_ttl_seconds=cache_ttl_seconds,
368
373
  fallback=fallback,
369
374
  max_retries=max_retries,
375
+ record_variables=record_variables,
370
376
  )
371
377
 
372
378
 
trodo/_version.py CHANGED
@@ -1 +1 @@
1
- SDK_VERSION = "3.0.6"
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:
@@ -78,6 +78,7 @@ def _to_prompt(
78
78
  raw: Dict[str, Any],
79
79
  is_fallback: bool = False,
80
80
  trace_label: Optional[str] = None,
81
+ record_variables: bool = False,
81
82
  ) -> ManagedPrompt:
82
83
  return ManagedPrompt(
83
84
  name=str(raw.get("name") or ""),
@@ -96,6 +97,7 @@ def _to_prompt(
96
97
  updated_at=raw.get("updated_at") or raw.get("updatedAt"),
97
98
  is_fallback=is_fallback,
98
99
  trace_label=trace_label,
100
+ record_variables=record_variables,
99
101
  )
100
102
 
101
103
 
@@ -191,6 +193,7 @@ class PromptManager:
191
193
  cache_ttl_seconds: Optional[float] = None,
192
194
  fallback: Optional[Dict[str, Any]] = None,
193
195
  max_retries: int = 2,
196
+ record_variables: bool = False,
194
197
  ) -> ManagedPrompt:
195
198
  """Fetch a managed prompt by name.
196
199
 
@@ -262,20 +265,20 @@ class PromptManager:
262
265
  if ttl > 0:
263
266
  fresh = self._cache.get_fresh(key)
264
267
  if fresh is not None:
265
- return _to_prompt(fresh, trace_label=trace_label)
268
+ return _to_prompt(fresh, trace_label=trace_label, record_variables=record_variables)
266
269
 
267
270
  stale = self._cache.get_stale(key)
268
271
  if stale is not None:
269
272
  # Serve immediately, refresh behind the caller's back. A slow or
270
273
  # dead API costs latency on nobody's request.
271
274
  self._cache.revalidate(key, fetcher, ttl)
272
- return _to_prompt(stale, trace_label=trace_label)
275
+ return _to_prompt(stale, trace_label=trace_label, record_variables=record_variables)
273
276
 
274
277
  try:
275
278
  raw = fetcher()
276
279
  if ttl > 0:
277
280
  self._cache.set(key, raw, ttl)
278
- return _to_prompt(raw, trace_label=trace_label)
281
+ return _to_prompt(raw, trace_label=trace_label, record_variables=record_variables)
279
282
  except Exception as e:
280
283
  # A config error is not an outage: a typo'd label silently serving
281
284
  # the fallback forever would hide the mistake for as long as it
@@ -284,7 +287,7 @@ class PromptManager:
284
287
  raise
285
288
  stale = self._cache.get_stale(key)
286
289
  if stale is not None:
287
- return _to_prompt(stale, trace_label=trace_label)
290
+ return _to_prompt(stale, trace_label=trace_label, record_variables=record_variables)
288
291
  if fallback:
289
292
  return _to_prompt(
290
293
  {
@@ -299,6 +302,8 @@ class PromptManager:
299
302
  "variables": fallback.get("variables") or [],
300
303
  },
301
304
  is_fallback=True,
305
+ trace_label=trace_label,
306
+ record_variables=record_variables,
302
307
  )
303
308
  raise
304
309
 
@@ -16,6 +16,7 @@ from typing import Any, Callable, Dict, Iterable, List, Optional
16
16
  from .context import get_active_context
17
17
  from .prompt_trace import (
18
18
  prompt_attributes,
19
+ prompt_list_attributes,
19
20
  prompt_ref_from_fingerprint,
20
21
  remember_prompt,
21
22
  )
@@ -407,7 +408,7 @@ class _OtelAdapter(_SpanProcessorBase): # type: ignore[valid-type,misc]
407
408
  # rewrites what a past span ran.
408
409
  state = getattr(ctx, "prompt_state", None)
409
410
  current = state.get("current") if isinstance(state, dict) else None
410
- for k, v in prompt_attributes(current).items():
411
+ for k, v in {**prompt_attributes(current), **prompt_list_attributes(state, current)}.items():
411
412
  set_attr(k, v)
412
413
  if isinstance(state, dict):
413
414
  if len(_span_prompt_state) >= _SPAN_STATE_MAX:
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:
@@ -31,13 +31,18 @@ from typing import Any, Dict, List, Optional, Tuple
31
31
 
32
32
  from .context import get_active_context
33
33
 
34
- # A PromptRef is a plain dict: {name, version_hash?, content_hash?, label?}.
34
+ # A PromptRef is a plain dict: {name, version_hash?, content_hash?, label?,
35
+ # version?, fallback?, variables?}. ``fallback`` marks the caller's own text,
36
+ # served because the prompt could not be fetched (no hash: not a version).
37
+ # ``variables`` are the compiled values, only when the caller asked.
35
38
  PromptRef = Dict[str, Any]
36
39
 
37
40
 
38
41
  def new_prompt_state() -> Dict[str, Any]:
39
42
  """Per-run accumulator, shared by reference across the run's span tree."""
40
- return {"current": None, "current_span_id": None, "all": []}
43
+ # by_span: the prompts compiled in each span, in order (deduped). One model
44
+ # call is often built from several -- a system prompt, a skill, a context.
45
+ return {"current": None, "current_span_id": None, "all": [], "by_span": {}}
41
46
 
42
47
 
43
48
  # Compiled prompt (or its messages list) -> the version it came from.
@@ -90,7 +95,7 @@ def remember_prompt(state: Any, ref: PromptRef) -> None:
90
95
 
91
96
 
92
97
  def _ref_key(ref: PromptRef) -> str:
93
- return ref.get("version_hash") or ref.get("name") or ""
98
+ return ref.get("version_hash") or ((ref.get("name") or "") + ("#fallback" if ref.get("fallback") else ""))
94
99
 
95
100
 
96
101
  def record_compiled_prompt(ref: PromptRef) -> None:
@@ -110,9 +115,48 @@ def record_compiled_prompt(ref: PromptRef) -> None:
110
115
  used: List[PromptRef] = state["all"]
111
116
  if not any(_ref_key(r) == key for r in used):
112
117
  used.append(ref)
118
+ here = state.setdefault("by_span", {}).setdefault(state["current_span_id"], [])
119
+ if not any(_ref_key(r) == key for r in here):
120
+ here.append(ref)
113
121
  _stamp_active_otel_span(ref)
114
122
 
115
123
 
124
+ #: Longest recorded variable value, and the most a span carries in all. Keep in sync with the Node SDK.
125
+ VARIABLE_VALUE_MAX_CHARS = 2000
126
+ VARIABLES_MAX_CHARS = 16000
127
+
128
+
129
+ def recordable_variables(values: Optional[Dict[str, Any]]) -> Optional[Dict[str, str]]:
130
+ """The values a prompt was compiled with, as strings, clipped.
131
+
132
+ Over the total cap nothing is recorded: a partial set would replay as a
133
+ different prompt. Strings follow JS rules (as the template engine does).
134
+ """
135
+ if not isinstance(values, dict):
136
+ return None
137
+ out: Dict[str, str] = {}
138
+ total = 0
139
+ for k, v in values.items():
140
+ if v is None:
141
+ s = ""
142
+ elif isinstance(v, str):
143
+ s = v
144
+ elif isinstance(v, bool):
145
+ s = "true" if v else "false"
146
+ else:
147
+ try:
148
+ s = json.dumps(v, separators=(",", ":"), ensure_ascii=False)
149
+ except Exception: # noqa: BLE001
150
+ s = str(v)
151
+ if len(s) > VARIABLE_VALUE_MAX_CHARS:
152
+ s = s[:VARIABLE_VALUE_MAX_CHARS] + "\u2026"
153
+ total += len(str(k)) + len(s)
154
+ if total > VARIABLES_MAX_CHARS:
155
+ return None
156
+ out[str(k)] = s
157
+ return out or None
158
+
159
+
116
160
  def prompt_attributes(ref: Optional[PromptRef]) -> Dict[str, str]:
117
161
  """Flatten a PromptRef to primitive span attributes (None values omitted)."""
118
162
  out: Dict[str, str] = {}
@@ -121,13 +165,47 @@ def prompt_attributes(ref: Optional[PromptRef]) -> Dict[str, str]:
121
165
  out["trodo.prompt.name"] = ref["name"]
122
166
  if ref.get("version_hash"):
123
167
  out["trodo.prompt.version_hash"] = ref["version_hash"]
168
+ if ref.get("version"):
169
+ out["trodo.prompt.version"] = str(ref["version"])
124
170
  if ref.get("label"):
125
171
  out["trodo.prompt.label"] = ref["label"]
126
172
  if ref.get("content_hash"):
127
173
  out["trodo.prompt.content_hash"] = ref["content_hash"]
174
+ if ref.get("fallback"):
175
+ out["trodo.prompt.fallback"] = "true"
176
+ if ref.get("variables"):
177
+ out["trodo.prompt.variables"] = json.dumps(ref["variables"], separators=(",", ":"), ensure_ascii=False)
128
178
  return out
129
179
 
130
180
 
181
+ def prompt_list_attributes(state: Any, main: Optional[PromptRef]) -> Dict[str, str]:
182
+ """``trodo.prompts`` for one span: every prompt compiled with ``main`` in the
183
+ same scope, when there is more than one. A JSON string (OTLP attributes are
184
+ primitives); ``trodo.prompt.*`` keeps naming the main one."""
185
+ if not isinstance(state, dict) or not main:
186
+ return {}
187
+ key = _ref_key(main)
188
+ for refs in (state.get("by_span") or {}).values():
189
+ if len(refs) > 1 and any(_ref_key(r) == key for r in refs):
190
+ items = []
191
+ for r in refs:
192
+ item: Dict[str, Any] = {"name": r.get("name")}
193
+ if r.get("version"):
194
+ item["version"] = r["version"]
195
+ if r.get("version_hash"):
196
+ item["version_hash"] = r["version_hash"]
197
+ if r.get("fallback"):
198
+ item["fallback"] = True
199
+ items.append(item)
200
+ return {"trodo.prompts": json.dumps(items, separators=(",", ":"), ensure_ascii=False)}
201
+ return {}
202
+
203
+
204
+ def run_prompt_list(refs: List[PromptRef]) -> List[PromptRef]:
205
+ """The run's prompt list: which prompts and versions -- values stay on the span."""
206
+ return [{k: v for k, v in r.items() if k != "variables"} for r in refs]
207
+
208
+
131
209
  def merge_prompt_attrs(
132
210
  active: Any,
133
211
  attrs: Optional[Dict[str, Any]],
@@ -150,6 +228,7 @@ def merge_prompt_attrs(
150
228
  if from_input is not None:
151
229
  remember_prompt(state, from_input)
152
230
  merged.update(prompt_attributes(from_input))
231
+ merged.update(prompt_list_attributes(state, from_input))
153
232
  elif isinstance(state, dict):
154
233
  # The run's "most recently compiled" prompt is a FALLBACK, used only
155
234
  # where it is defensible. Applying it to every span meant compiling a
@@ -169,6 +248,7 @@ def merge_prompt_attrs(
169
248
  )
170
249
  if kind == "llm" or compiled_here:
171
250
  merged.update(prompt_attributes(state.get("current")))
251
+ merged.update(prompt_list_attributes(state, state.get("current")))
172
252
  return merged or None
173
253
 
174
254
 
@@ -184,7 +264,9 @@ def _stamp_active_otel_span(ref: PromptRef) -> None:
184
264
  span = trace.get_current_span()
185
265
  if span is None:
186
266
  return
187
- for k, v in prompt_attributes(ref).items():
267
+ active = get_active_context()
268
+ state = getattr(active, "prompt_state", None) if active is not None else None
269
+ for k, v in {**prompt_attributes(ref), **prompt_list_attributes(state, ref)}.items():
188
270
  span.set_attribute(k, v)
189
271
  except Exception: # noqa: BLE001
190
272
  pass # not in OTLP mode / opentelemetry not installed — no-op
trodo/otel/wrap_agent.py CHANGED
@@ -37,6 +37,7 @@ from .prompt_trace import (
37
37
  new_prompt_state,
38
38
  prompt_ref_from_carrier,
39
39
  remember_prompt,
40
+ run_prompt_list,
40
41
  )
41
42
  from .processor import TrodoSpanProcessor, TrodoRun, TrodoSpan
42
43
  from .transport import get_transport_mode, get_otel_tracer, get_otel_helpers
@@ -693,7 +694,7 @@ class wrap_agent:
693
694
  # exactly when you still want to know who the user was.
694
695
  user=self._user,
695
696
  attributes=(
696
- {"trodo.prompts": self._ctx.prompt_state["all"]}
697
+ {"trodo.prompts": run_prompt_list(self._ctx.prompt_state["all"])}
697
698
  if self._ctx is not None
698
699
  and self._ctx.prompt_state
699
700
  and self._ctx.prompt_state["all"]
trodo/prompts/template.py CHANGED
@@ -70,6 +70,14 @@ def parse(template: Optional[str]) -> List[Token]:
70
70
  if i < len(src):
71
71
  push({"t": "text", "v": src[i:]})
72
72
  break
73
+ # ESCAPE: \{{...}} is literal text -- the backslash goes, the tag stays
74
+ # as written and is neither a variable nor an error.
75
+ if open_at > 0 and src[open_at - 1] == "\\":
76
+ end = src.find(_CLOSE, open_at + len(_OPEN))
77
+ stop = len(src) if end == -1 else end + len(_CLOSE)
78
+ push({"t": "text", "v": src[i : open_at - 1] + src[open_at:stop]})
79
+ i = stop
80
+ continue
73
81
  if open_at > i:
74
82
  push({"t": "text", "v": src[i:open_at]})
75
83
 
trodo/prompts/types.py CHANGED
@@ -81,6 +81,9 @@ class ManagedPrompt:
81
81
  #: PromptManager.get(); not part of the wire contract. ``repr=False`` /
82
82
  #: ``compare=False`` so it never affects equality or reprs.
83
83
  trace_label: Optional[str] = field(default=None, repr=False, compare=False)
84
+ #: Record compiled values on the span (``trodo.prompt.variables``). Set by
85
+ #: PromptManager.get(record_variables=True); off by default (user data).
86
+ record_variables: bool = field(default=False, repr=False, compare=False)
84
87
 
85
88
  def compile(self, variables: Optional[Dict[str, Any]] = None, **kwargs: Any) -> CompiledPrompt:
86
89
  """Compile with variable values, as a dict or as keyword arguments."""
@@ -89,38 +92,48 @@ class ManagedPrompt:
89
92
  values = dict(variables or {})
90
93
  values.update(kwargs)
91
94
  compiled = compile_prompt(self, values)
92
- # Prompt traceability. Never records a fallback — it has no real hash,
93
- # so a link to it would name a version that does not exist.
94
- if not self.is_fallback:
95
- try:
96
- from ..otel.prompt_trace import (
97
- record_compiled_prompt,
98
- register_compiled_messages,
99
- tag_carrier_with_prompt,
100
- )
101
-
95
+ # Prompt traceability. A fallback is recorded too, marked as one and
96
+ # with no hash: a span that ran the caller's own text says so.
97
+ try:
98
+ from ..otel.prompt_trace import (
99
+ record_compiled_prompt,
100
+ register_compiled_messages,
101
+ tag_carrier_with_prompt,
102
+ )
103
+
104
+ from ..otel.prompt_trace import recordable_variables
105
+
106
+ if self.is_fallback:
107
+ ref: Dict[str, Any] = {"name": self.name, "label": self.trace_label, "fallback": True}
108
+ else:
102
109
  ref = {
103
110
  "name": self.name,
104
111
  "version_hash": self.version_hash,
105
112
  "content_hash": self.content_hash,
106
113
  "label": self.trace_label,
114
+ "version": self.version or None,
107
115
  }
108
- # (1) the surrounding run scope, if any — the only route that
109
- # reaches auto-instrumented spans, whose input we never see.
110
- record_compiled_prompt(ref)
111
- # (2) the compiled value itself, so a span handed these messages
112
- # as ``input`` recovers the version even when compile() ran
113
- # outside the run. Both the wrapper and the list are tagged,
114
- # since callers pass one or the other.
115
- tag_carrier_with_prompt(compiled, ref)
116
- tag_carrier_with_prompt(getattr(compiled, "messages", None), ref)
117
- # (3) a content fingerprint, so an auto-instrumented provider
118
- # span handed exactly these messages (compiled before the
119
- # run; no carrier on the serialised input) links by exact
120
- # match.
116
+ if self.record_variables:
117
+ ref["variables"] = recordable_variables(values)
118
+ # (1) the surrounding run scope, if any — the only route that
119
+ # reaches auto-instrumented spans, whose input we never see.
120
+ record_compiled_prompt(ref)
121
+ # (2) the compiled value itself, so a span handed these messages
122
+ # as ``input`` recovers the version even when compile() ran
123
+ # outside the run. Both the wrapper and the list are tagged,
124
+ # since callers pass one or the other.
125
+ tag_carrier_with_prompt(compiled, ref)
126
+ tag_carrier_with_prompt(getattr(compiled, "messages", None), ref)
127
+ # (3) a content fingerprint, so an auto-instrumented provider
128
+ # span handed exactly these messages (compiled before the
129
+ # run; no carrier on the serialised input) links by exact
130
+ # match. Not for a fallback: its text may equal a real
131
+ # version's, and an exact match must never swap a real
132
+ # version for "fallback".
133
+ if not self.is_fallback:
121
134
  register_compiled_messages(getattr(compiled, "messages", None), ref)
122
- except Exception: # noqa: BLE001
123
- pass # traceability must never break compile
135
+ except Exception: # noqa: BLE001
136
+ pass # traceability must never break compile
124
137
  return compiled
125
138
 
126
139
 
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: trodo-python
3
- Version: 3.0.6
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
- trodo/__init__.py,sha256=0x6Zrt4j0wpRaGSxvVzJW8lh_2DNRHcBiVKrMM8mUEk,27233
2
- trodo/_version.py,sha256=qKwdJvcO3P8QjaYxAoRx_NCIZfhAAd-DtBQpYCR4_Wc,22
1
+ trodo/__init__.py,sha256=tG--Ls4hitU3XD4Krnt5eP-sIQRrfCZJsnmHyrXArtY,27509
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,26 +12,26 @@ 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
19
19
  trodo/managers/people_manager.py,sha256=mMVnx40Mlifx6NGgChvohC9ViK6dQu2mkXNHbV8pK1E,2882
20
- trodo/managers/prompt_manager.py,sha256=qFVHgh7PW-SlgHp62ybirdYsJBg-fcQVMTTU3jPqFvo,13435
20
+ trodo/managers/prompt_manager.py,sha256=9IB9iaLpI4DGCRXsUUm08RlejzlS1llXZQtVKJdXpMQ,13794
21
21
  trodo/managers/user_manager.py,sha256=faJYX3CHrD7ulYiShV7FhThSMX9aJ3kdOgU4Qtdy5FM,2844
22
22
  trodo/otel/__init__.py,sha256=yiRFXWUU45bAM2CV37XeO7zf1hmnmjufdP4XO50yEyE,624
23
- trodo/otel/auto_instrument.py,sha256=M5YVpFoPqn9bQohDFM7yyADrVGJPqFBToJLnBO7nOSA,29029
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
27
- trodo/otel/prompt_trace.py,sha256=-kywRBU0Q2gWntS9HU-P5i7Kc5U-IJU7UVLjkdC2jw4,13593
26
+ trodo/otel/processor.py,sha256=hMX-gHpgzk36_lDVsV7pcQOG6YPIhA3hFOuhNPqrbNQ,15528
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
30
- trodo/otel/wrap_agent.py,sha256=qx2jnuVIMZTv-PpRt-qFWqMWz1YO4jqY5pwgBQirVDo,44519
30
+ trodo/otel/wrap_agent.py,sha256=PTQ_rba4PcO2zGSW-ZrKMGH0dtvccP3v8gZI9CxulyA,44557
31
31
  trodo/prompts/__init__.py,sha256=yunNc8WkTSfEEkRR-NZWXAt_ZB3Ee2INRh-4RE7uHj4,806
32
32
  trodo/prompts/compile.py,sha256=XoKDKz6Yaofhrk-87AVW-SnwbiXLvfp161AL2bAFzNY,8802
33
- trodo/prompts/template.py,sha256=eGO2ZVNOw6JK7Ffj1UCYDMJFYyX5qQW2POlmFJSQpAo,9975
34
- trodo/prompts/types.py,sha256=Mjn6x6f7dI3TIVHSvzM2xs_gchuh5sCwUfBsW-YLVm0,5654
33
+ trodo/prompts/template.py,sha256=nNGUcIoIk2ekBx0nkNYn4b9moDwiEu61Z94zs651Byg,10411
34
+ trodo/prompts/types.py,sha256=-Ko45D-erRElSvdJYiOO-OPsX8S9MOtXmUjo9N4OKEU,6340
35
35
  trodo/queue/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
36
36
  trodo/queue/batch_flusher.py,sha256=4Lg6T3Urwi9U0Q4FpFGPmjDYKg4ZliCTR-ND8BJvWaY,1298
37
37
  trodo/queue/event_queue.py,sha256=EVFZrhlq_kwC3jJ2GK0wMhHISf9UzLCZNDnT_aZ2I2A,872
@@ -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.6.dist-info/METADATA,sha256=vX_4eP5iK-7twSVt1H3g-MxznSLTdbipCK9E1WJxlAg,25307
44
- trodo_python-3.0.6.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
45
- trodo_python-3.0.6.dist-info/top_level.txt,sha256=VCQu1CJWFmNsqTs1YxMcw4Mq35Tc3z3uI9RwHEXAayQ,6
46
- trodo_python-3.0.6.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,,