trodo-python 3.0.6__tar.gz → 3.1.0__tar.gz
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_python-3.0.6 → trodo_python-3.1.0}/PKG-INFO +1 -1
- {trodo_python-3.0.6 → trodo_python-3.1.0}/pyproject.toml +1 -1
- trodo_python-3.1.0/tests/test_processor_methods.py +88 -0
- {trodo_python-3.0.6 → trodo_python-3.1.0}/tests/test_prompt_trace.py +79 -6
- {trodo_python-3.0.6 → trodo_python-3.1.0}/tests/test_sender.py +73 -3
- {trodo_python-3.0.6 → trodo_python-3.1.0}/trodo/__init__.py +6 -0
- trodo_python-3.1.0/trodo/_version.py +1 -0
- {trodo_python-3.0.6 → trodo_python-3.1.0}/trodo/delivery/sender.py +91 -14
- {trodo_python-3.0.6 → trodo_python-3.1.0}/trodo/managers/prompt_manager.py +9 -4
- {trodo_python-3.0.6 → trodo_python-3.1.0}/trodo/otel/auto_instrument.py +2 -1
- {trodo_python-3.0.6 → trodo_python-3.1.0}/trodo/otel/processor.py +78 -14
- {trodo_python-3.0.6 → trodo_python-3.1.0}/trodo/otel/prompt_trace.py +86 -4
- {trodo_python-3.0.6 → trodo_python-3.1.0}/trodo/otel/wrap_agent.py +2 -1
- {trodo_python-3.0.6 → trodo_python-3.1.0}/trodo/prompts/template.py +8 -0
- {trodo_python-3.0.6 → trodo_python-3.1.0}/trodo/prompts/types.py +38 -25
- {trodo_python-3.0.6 → trodo_python-3.1.0}/trodo_python.egg-info/PKG-INFO +1 -1
- trodo_python-3.0.6/tests/test_processor_methods.py +0 -34
- trodo_python-3.0.6/trodo/_version.py +0 -1
- {trodo_python-3.0.6 → trodo_python-3.1.0}/README.md +0 -0
- {trodo_python-3.0.6 → trodo_python-3.1.0}/setup.cfg +0 -0
- {trodo_python-3.0.6 → trodo_python-3.1.0}/tests/test_anon_distinct_id.py +0 -0
- {trodo_python-3.0.6 → trodo_python-3.1.0}/tests/test_auto_instrument_fixes.py +0 -0
- {trodo_python-3.0.6 → trodo_python-3.1.0}/tests/test_cross_process_session.py +0 -0
- {trodo_python-3.0.6 → trodo_python-3.1.0}/tests/test_datasets.py +0 -0
- {trodo_python-3.0.6 → trodo_python-3.1.0}/tests/test_end_run.py +0 -0
- {trodo_python-3.0.6 → trodo_python-3.1.0}/tests/test_end_run_order.py +0 -0
- {trodo_python-3.0.6 → trodo_python-3.1.0}/tests/test_error_enrichment.py +0 -0
- {trodo_python-3.0.6 → trodo_python-3.1.0}/tests/test_framework_deference.py +0 -0
- {trodo_python-3.0.6 → trodo_python-3.1.0}/tests/test_get_prompt_version_types.py +0 -0
- {trodo_python-3.0.6 → trodo_python-3.1.0}/tests/test_instrumentor_resolution.py +0 -0
- {trodo_python-3.0.6 → trodo_python-3.1.0}/tests/test_llm_usage_cost.py +0 -0
- {trodo_python-3.0.6 → trodo_python-3.1.0}/tests/test_long_runs.py +0 -0
- {trodo_python-3.0.6 → trodo_python-3.1.0}/tests/test_multi_agent_shape.py +0 -0
- {trodo_python-3.0.6 → trodo_python-3.1.0}/tests/test_prompt_fingerprint.py +0 -0
- {trodo_python-3.0.6 → trodo_python-3.1.0}/tests/test_prompts.py +0 -0
- {trodo_python-3.0.6 → trodo_python-3.1.0}/tests/test_register_otel.py +0 -0
- {trodo_python-3.0.6 → trodo_python-3.1.0}/tests/test_start_run.py +0 -0
- {trodo_python-3.0.6 → trodo_python-3.1.0}/tests/test_user_traits.py +0 -0
- {trodo_python-3.0.6 → trodo_python-3.1.0}/tests/test_wrap_agent_unchanged.py +0 -0
- {trodo_python-3.0.6 → trodo_python-3.1.0}/trodo/api/__init__.py +0 -0
- {trodo_python-3.0.6 → trodo_python-3.1.0}/trodo/api/_retry.py +0 -0
- {trodo_python-3.0.6 → trodo_python-3.1.0}/trodo/api/async_client.py +0 -0
- {trodo_python-3.0.6 → trodo_python-3.1.0}/trodo/api/endpoints.py +0 -0
- {trodo_python-3.0.6 → trodo_python-3.1.0}/trodo/api/http_client.py +0 -0
- {trodo_python-3.0.6 → trodo_python-3.1.0}/trodo/api/management.py +0 -0
- {trodo_python-3.0.6 → trodo_python-3.1.0}/trodo/auto/__init__.py +0 -0
- {trodo_python-3.0.6 → trodo_python-3.1.0}/trodo/auto/auto_event_manager.py +0 -0
- {trodo_python-3.0.6 → trodo_python-3.1.0}/trodo/client.py +0 -0
- {trodo_python-3.0.6 → trodo_python-3.1.0}/trodo/delivery/__init__.py +0 -0
- {trodo_python-3.0.6 → trodo_python-3.1.0}/trodo/managers/__init__.py +0 -0
- {trodo_python-3.0.6 → trodo_python-3.1.0}/trodo/managers/dataset_manager.py +0 -0
- {trodo_python-3.0.6 → trodo_python-3.1.0}/trodo/managers/group_manager.py +0 -0
- {trodo_python-3.0.6 → trodo_python-3.1.0}/trodo/managers/people_manager.py +0 -0
- {trodo_python-3.0.6 → trodo_python-3.1.0}/trodo/managers/user_manager.py +0 -0
- {trodo_python-3.0.6 → trodo_python-3.1.0}/trodo/otel/__init__.py +0 -0
- {trodo_python-3.0.6 → trodo_python-3.1.0}/trodo/otel/context.py +0 -0
- {trodo_python-3.0.6 → trodo_python-3.1.0}/trodo/otel/helpers.py +0 -0
- {trodo_python-3.0.6 → trodo_python-3.1.0}/trodo/otel/register.py +0 -0
- {trodo_python-3.0.6 → trodo_python-3.1.0}/trodo/otel/transport.py +0 -0
- {trodo_python-3.0.6 → trodo_python-3.1.0}/trodo/prompts/__init__.py +0 -0
- {trodo_python-3.0.6 → trodo_python-3.1.0}/trodo/prompts/compile.py +0 -0
- {trodo_python-3.0.6 → trodo_python-3.1.0}/trodo/queue/__init__.py +0 -0
- {trodo_python-3.0.6 → trodo_python-3.1.0}/trodo/queue/batch_flusher.py +0 -0
- {trodo_python-3.0.6 → trodo_python-3.1.0}/trodo/queue/event_queue.py +0 -0
- {trodo_python-3.0.6 → trodo_python-3.1.0}/trodo/session/__init__.py +0 -0
- {trodo_python-3.0.6 → trodo_python-3.1.0}/trodo/session/server_session.py +0 -0
- {trodo_python-3.0.6 → trodo_python-3.1.0}/trodo/session/session_manager.py +0 -0
- {trodo_python-3.0.6 → trodo_python-3.1.0}/trodo/types.py +0 -0
- {trodo_python-3.0.6 → trodo_python-3.1.0}/trodo/user_context.py +0 -0
- {trodo_python-3.0.6 → trodo_python-3.1.0}/trodo/util/__init__.py +0 -0
- {trodo_python-3.0.6 → trodo_python-3.1.0}/trodo/util/lru.py +0 -0
- {trodo_python-3.0.6 → trodo_python-3.1.0}/trodo_python.egg-info/SOURCES.txt +0 -0
- {trodo_python-3.0.6 → trodo_python-3.1.0}/trodo_python.egg-info/dependency_links.txt +0 -0
- {trodo_python-3.0.6 → trodo_python-3.1.0}/trodo_python.egg-info/requires.txt +0 -0
- {trodo_python-3.0.6 → trodo_python-3.1.0}/trodo_python.egg-info/top_level.txt +0 -0
|
@@ -0,0 +1,88 @@
|
|
|
1
|
+
"""Direct unit tests of TrodoSpanProcessor.start_run / .end_run."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
from trodo.otel.processor import TrodoRun, TrodoSpan, TrodoSpanProcessor
|
|
5
|
+
|
|
6
|
+
|
|
7
|
+
def test_start_run_posts_to_runs_start(processor, http):
|
|
8
|
+
run = TrodoRun(run_id="r1", agent_name="x", status="running")
|
|
9
|
+
processor.start_run(run)
|
|
10
|
+
assert len(http.run_start) == 1
|
|
11
|
+
assert http.run_start[0]["run"]["run_id"] == "r1"
|
|
12
|
+
assert http.run_start[0]["run"]["status"] == "running"
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
def test_end_run_posts_to_runs_end(processor, http):
|
|
16
|
+
processor.end_run("r1", {"status": "ok", "ended_at": "2026-04-30T00:00:00Z"})
|
|
17
|
+
assert len(http.run_end) == 1
|
|
18
|
+
rid, payload = http.run_end[0]
|
|
19
|
+
assert rid == "r1"
|
|
20
|
+
assert payload["status"] == "ok"
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def test_start_run_swallows_http_errors(processor, http):
|
|
24
|
+
http.fail_next = True
|
|
25
|
+
run = TrodoRun(run_id="r1", agent_name="x")
|
|
26
|
+
# Must not raise.
|
|
27
|
+
processor.start_run(run)
|
|
28
|
+
assert len(http.run_start) == 0
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def test_end_run_swallows_http_errors(processor, http):
|
|
32
|
+
http.fail_next = True
|
|
33
|
+
processor.end_run("r1", {"status": "ok"})
|
|
34
|
+
assert len(http.run_end) == 0
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
# ── Span buffers are bounded ─────────────────────────────────────────────────
|
|
38
|
+
|
|
39
|
+
def _span(run_id: str, span_id: str) -> TrodoSpan:
|
|
40
|
+
return TrodoSpan(span_id=span_id, run_id=run_id, parent_span_id=None, kind="llm", name=span_id)
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def test_end_run_forgets_a_run_that_was_never_joined(processor, http):
|
|
44
|
+
processor.enqueue_span(_span("r1", "s1"))
|
|
45
|
+
assert processor.tracked_runs() == 1
|
|
46
|
+
processor.end_run("r1", {"status": "ok"})
|
|
47
|
+
assert processor.tracked_runs() == 0
|
|
48
|
+
assert processor.get_pending("r1") == []
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
def test_a_run_with_no_span_for_run_idle_s_is_forgotten_and_its_spans_go_ahead(http):
|
|
52
|
+
clock = [0.0]
|
|
53
|
+
p = TrodoSpanProcessor(http_client=http, run_idle_s=1.0, now=lambda: clock[0])
|
|
54
|
+
p.enqueue_span(_span("otel", "s1")) # never finalised
|
|
55
|
+
clock[0] = 2.0
|
|
56
|
+
p.enqueue_span(_span("live", "s2"))
|
|
57
|
+
assert p.tracked_runs() == 1
|
|
58
|
+
assert p.get_pending("otel") == []
|
|
59
|
+
assert [(rid, [s["span_id"] for s in spans]) for rid, spans in http.spans_append] == [("otel", ["s1"])]
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
def test_at_most_max_tracked_runs_are_held_least_recently_active_first(http):
|
|
63
|
+
p = TrodoSpanProcessor(http_client=http, max_tracked_runs=2)
|
|
64
|
+
p.enqueue_span(_span("a", "a1")); p.enqueue_span(_span("b", "b1"))
|
|
65
|
+
p.enqueue_span(_span("a", "a2")) # a is now the most recent
|
|
66
|
+
p.enqueue_span(_span("c", "c1"))
|
|
67
|
+
assert p.tracked_runs() == 2
|
|
68
|
+
assert p.get_pending("b") == []
|
|
69
|
+
assert len(p.get_pending("a")) == 2
|
|
70
|
+
assert [rid for rid, _ in http.spans_append] == ["b"]
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
def test_two_joins_of_one_run_stay_joined_until_the_last_ends(processor, http):
|
|
74
|
+
processor.mark_joined("r1"); processor.mark_joined("r1")
|
|
75
|
+
processor.unmark_joined("r1") # the first join ends
|
|
76
|
+
processor.enqueue_span(_span("r1", "s1"))
|
|
77
|
+
assert [rid for rid, _ in http.spans_append] == ["r1"] # still forwarded at once
|
|
78
|
+
processor.unmark_joined("r1") # the last join ends
|
|
79
|
+
processor.enqueue_span(_span("r1", "s2"))
|
|
80
|
+
assert len(http.spans_append) == 1 # buffered locally again
|
|
81
|
+
assert [s.span_id for s in processor.get_pending("r1")] == ["s2"]
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
def test_end_run_does_not_end_a_join_still_open(processor, http):
|
|
85
|
+
processor.mark_joined("r1")
|
|
86
|
+
processor.end_run("r1", {"status": "ok"})
|
|
87
|
+
processor.enqueue_span(_span("r1", "s1"))
|
|
88
|
+
assert [rid for rid, _ in http.spans_append] == ["r1"]
|
|
@@ -90,7 +90,7 @@ def test_no_op_outside_a_run(processor, http):
|
|
|
90
90
|
assert len(http.run_ingest) == 0
|
|
91
91
|
|
|
92
92
|
|
|
93
|
-
def
|
|
93
|
+
def test_a_fallback_is_traced_by_name_marked_with_no_hash(processor, http):
|
|
94
94
|
mgr = PromptManager(PromptHttp(fail=True))
|
|
95
95
|
with wrap_agent(processor=processor, team_site_id="site-x", agent_name="chat"):
|
|
96
96
|
p = mgr.get(
|
|
@@ -108,9 +108,80 @@ def test_fallback_prompt_is_not_traced(processor, http):
|
|
|
108
108
|
|
|
109
109
|
spans = http.run_ingest[0]["spans"]
|
|
110
110
|
attrs = next(s for s in spans if s["name"] == "llm").get("attributes") or {}
|
|
111
|
-
assert "trodo.prompt.name"
|
|
112
|
-
|
|
113
|
-
assert "
|
|
111
|
+
assert attrs["trodo.prompt.name"] == "refund-agent"
|
|
112
|
+
assert attrs["trodo.prompt.fallback"] == "true"
|
|
113
|
+
assert "trodo.prompt.version_hash" not in attrs
|
|
114
|
+
assert "trodo.prompt.version" not in attrs
|
|
115
|
+
assert http.run_ingest[0]["run"]["attributes"]["trodo.prompts"] == [
|
|
116
|
+
{"name": "refund-agent", "label": "production", "fallback": True}
|
|
117
|
+
]
|
|
118
|
+
|
|
119
|
+
|
|
120
|
+
def test_stamps_the_version_number_beside_the_hash(processor, http):
|
|
121
|
+
mgr = PromptManager(PromptHttp(prompt=PROMPT_WIRE))
|
|
122
|
+
with wrap_agent(processor=processor, team_site_id="site-x", agent_name="chat"):
|
|
123
|
+
p = mgr.get("refund-agent")
|
|
124
|
+
with span("llm"):
|
|
125
|
+
p.compile(q="x")
|
|
126
|
+
attrs = next(s for s in http.run_ingest[0]["spans"] if s["name"] == "llm").get("attributes") or {}
|
|
127
|
+
assert attrs["trodo.prompt.version_hash"] == "a3f9c2e8d1b04756"
|
|
128
|
+
assert attrs["trodo.prompt.version"] == "3"
|
|
129
|
+
|
|
130
|
+
|
|
131
|
+
class TwoPromptHttp(PromptHttp):
|
|
132
|
+
def get_prompt(self, name, label=None, version=None):
|
|
133
|
+
if name == "refund-agent":
|
|
134
|
+
return {"prompt": dict(PROMPT_WIRE)}
|
|
135
|
+
return {"prompt": {**PROMPT_WIRE, "name": name, "version": 7, "version_hash": "b1b2b3b4b5b6b7b8", "content_hash": "other"}}
|
|
136
|
+
|
|
137
|
+
|
|
138
|
+
def test_a_span_built_from_several_prompts_lists_them_all(processor, http):
|
|
139
|
+
import json
|
|
140
|
+
|
|
141
|
+
mgr = PromptManager(TwoPromptHttp())
|
|
142
|
+
with wrap_agent(processor=processor, team_site_id="site-x", agent_name="chat"):
|
|
143
|
+
system = mgr.get("refund-agent")
|
|
144
|
+
skill = mgr.get("refund-skill")
|
|
145
|
+
with span("llm"):
|
|
146
|
+
system.compile(q="system part")
|
|
147
|
+
skill.compile(q="skill part")
|
|
148
|
+
attrs = next(s for s in http.run_ingest[0]["spans"] if s["name"] == "llm").get("attributes") or {}
|
|
149
|
+
assert attrs["trodo.prompt.name"] == "refund-skill"
|
|
150
|
+
assert json.loads(attrs["trodo.prompts"]) == [
|
|
151
|
+
{"name": "refund-agent", "version": 3, "version_hash": "a3f9c2e8d1b04756"},
|
|
152
|
+
{"name": "refund-skill", "version": 7, "version_hash": "b1b2b3b4b5b6b7b8"},
|
|
153
|
+
]
|
|
154
|
+
|
|
155
|
+
|
|
156
|
+
def test_one_prompt_is_not_a_list(processor, http):
|
|
157
|
+
mgr = PromptManager(PromptHttp(prompt=PROMPT_WIRE))
|
|
158
|
+
with wrap_agent(processor=processor, team_site_id="site-x", agent_name="chat"):
|
|
159
|
+
p = mgr.get("refund-agent")
|
|
160
|
+
with span("llm"):
|
|
161
|
+
p.compile(q="a")
|
|
162
|
+
p.compile(q="b")
|
|
163
|
+
attrs = next(s for s in http.run_ingest[0]["spans"] if s["name"] == "llm").get("attributes") or {}
|
|
164
|
+
assert "trodo.prompts" not in attrs
|
|
165
|
+
|
|
166
|
+
|
|
167
|
+
def test_records_compiled_values_only_when_asked(processor, http):
|
|
168
|
+
import json
|
|
169
|
+
|
|
170
|
+
mgr = PromptManager(PromptHttp(prompt=PROMPT_WIRE))
|
|
171
|
+
with wrap_agent(processor=processor, team_site_id="site-x", agent_name="chat"):
|
|
172
|
+
quiet = mgr.get("refund-agent", cache_ttl_seconds=0)
|
|
173
|
+
with span("quiet"):
|
|
174
|
+
quiet.compile(q="secret")
|
|
175
|
+
loud = mgr.get("refund-agent", cache_ttl_seconds=0, record_variables=True)
|
|
176
|
+
with span("loud"):
|
|
177
|
+
loud.compile(q="shown")
|
|
178
|
+
spans = http.run_ingest[0]["spans"]
|
|
179
|
+
quiet_attrs = next(s for s in spans if s["name"] == "quiet").get("attributes") or {}
|
|
180
|
+
loud_attrs = next(s for s in spans if s["name"] == "loud").get("attributes") or {}
|
|
181
|
+
assert "trodo.prompt.variables" not in quiet_attrs
|
|
182
|
+
assert json.loads(loud_attrs["trodo.prompt.variables"]) == {"q": "shown"}
|
|
183
|
+
# Values stay on the span; the run's list says which prompts, not what was in them.
|
|
184
|
+
assert all("variables" not in r for r in http.run_ingest[0]["run"]["attributes"]["trodo.prompts"])
|
|
114
185
|
|
|
115
186
|
|
|
116
187
|
# ── compiled OUTSIDE the run ────────────────────────────────────────────────
|
|
@@ -206,7 +277,7 @@ def test_hand_written_messages_are_not_carriers(processor, http):
|
|
|
206
277
|
assert "trodo.prompt.name" not in attrs
|
|
207
278
|
|
|
208
279
|
|
|
209
|
-
def
|
|
280
|
+
def test_a_fallback_via_the_input_route_is_marked_as_one(processor, http):
|
|
210
281
|
mgr = PromptManager(PromptHttp(fail=True))
|
|
211
282
|
p = mgr.get(
|
|
212
283
|
"refund-agent",
|
|
@@ -222,7 +293,9 @@ def test_a_fallback_is_never_tagged_via_the_input_route(processor, http):
|
|
|
222
293
|
pass
|
|
223
294
|
|
|
224
295
|
attrs = next(s for s in http.run_ingest[0]["spans"] if s["name"] == "llm").get("attributes") or {}
|
|
225
|
-
assert "trodo.prompt.name"
|
|
296
|
+
assert attrs["trodo.prompt.name"] == "refund-agent"
|
|
297
|
+
assert attrs["trodo.prompt.fallback"] == "true"
|
|
298
|
+
assert "trodo.prompt.version_hash" not in attrs
|
|
226
299
|
|
|
227
300
|
|
|
228
301
|
def test_carrier_table_is_bounded(processor, http):
|
|
@@ -325,7 +325,7 @@ def test_server_held_items_count_as_sent_and_warn_once(capsys):
|
|
|
325
325
|
def test_exit_says_loudly_what_was_not_delivered(capsys):
|
|
326
326
|
full = (200, None, {"results": [{"status": 429, "deferred": True, "reason": "backlog_full", "ceiling_units_min": 60,
|
|
327
327
|
"retry_after_seconds": 30, "message": "this team's backlog is full"}], "retry_after_ms": 30000})
|
|
328
|
-
s = Server([full])
|
|
328
|
+
s = Server([full, full]) # the exit hand-off is refused too: the backlog is full
|
|
329
329
|
sender = Sender(s, **fast(exit_flush_s=0.3))
|
|
330
330
|
sender.enqueue(run("a"))
|
|
331
331
|
assert wait_for(lambda: len(s.posts) == 1)
|
|
@@ -460,13 +460,22 @@ def test_exit_hand_off_does_not_wait_behind_slow_requests(capsys):
|
|
|
460
460
|
assert "150 trace item(s) were sent, but Trodo had not confirmed them" in err
|
|
461
461
|
|
|
462
462
|
|
|
463
|
+
class SlowLiveFullBacklog(SlowLive):
|
|
464
|
+
"""Ordinary requests take seconds; the exit hand-off is refused: the team's backlog is full."""
|
|
465
|
+
|
|
466
|
+
def post_raw(self, path, body, timeout=0, gzip_body=True):
|
|
467
|
+
if not body.get("exiting"):
|
|
468
|
+
return super().post_raw(path, body, timeout, gzip_body)
|
|
469
|
+
full = {"status": 429, "deferred": True, "retry_after_seconds": 30, "message": "this team's backlog is full"}
|
|
470
|
+
return 200, None, {"results": [dict(full) for _ in body["items"]], "retry_after_ms": 30000}
|
|
471
|
+
|
|
472
|
+
|
|
463
473
|
def test_exit_warning_counts_items_not_requests(capsys):
|
|
464
|
-
s =
|
|
474
|
+
s = SlowLiveFullBacklog(1.5)
|
|
465
475
|
sender = Sender(s, **fast(flush_at=50, max_in_flight=1, exit_flush_s=0.2))
|
|
466
476
|
for i in range(50):
|
|
467
477
|
sender.enqueue(run(f"live{i}"))
|
|
468
478
|
assert wait_for(lambda: sender.stats()["in_flight"] == 1)
|
|
469
|
-
sender._paused_until = time.time() + 60 # nothing else can go out
|
|
470
479
|
for i in range(7):
|
|
471
480
|
sender.enqueue(run(f"late{i}"))
|
|
472
481
|
sender._atexit()
|
|
@@ -475,6 +484,54 @@ def test_exit_warning_counts_items_not_requests(capsys):
|
|
|
475
484
|
assert "50 more were sent, but Trodo had not confirmed them yet." in err
|
|
476
485
|
|
|
477
486
|
|
|
487
|
+
# ── Lifecycle: exiting is the exit flush only ────────────────────────────────
|
|
488
|
+
|
|
489
|
+
def test_the_exit_hand_off_does_not_wait_out_a_429_pause():
|
|
490
|
+
s = Server([(429, "30", {"error": "Rate ceiling exceeded", "retry_after_seconds": 30})])
|
|
491
|
+
sender = Sender(s, **fast())
|
|
492
|
+
sender.enqueue(run("a"))
|
|
493
|
+
assert wait_for(lambda: sender.stats()["state"] == "paused")
|
|
494
|
+
t0 = time.time()
|
|
495
|
+
sender._atexit()
|
|
496
|
+
assert time.time() - t0 < 1.0
|
|
497
|
+
assert len(s.posts) == 2
|
|
498
|
+
assert s.posts[1]["body"]["exiting"] is True and s.posts[1]["body"]["items"] == [run("a")]
|
|
499
|
+
assert sender.stats()["sent"] == 1 and sender.stats()["queued"] == 0
|
|
500
|
+
|
|
501
|
+
|
|
502
|
+
def test_flush_waits_out_a_429_pause_within_its_bound():
|
|
503
|
+
s = Server([(429, "0.6", {"error": "Rate ceiling exceeded", "retry_after_seconds": 0.6})])
|
|
504
|
+
sender = Sender(s, **fast())
|
|
505
|
+
sender.enqueue(run("a"))
|
|
506
|
+
assert wait_for(lambda: sender.stats()["state"] == "paused")
|
|
507
|
+
t0 = time.time()
|
|
508
|
+
sender.flush(timeout_s=0.1)
|
|
509
|
+
assert time.time() - t0 < 0.4 and len(s.posts) == 1 # the bound held
|
|
510
|
+
sender.flush()
|
|
511
|
+
assert len(s.posts) == 2
|
|
512
|
+
assert sender.stats()["state"] == "idle" and sender.stats()["sent"] == 1
|
|
513
|
+
|
|
514
|
+
|
|
515
|
+
def test_atexit_flushes_once():
|
|
516
|
+
s = Server()
|
|
517
|
+
sender = Sender(s, **fast(flush_interval_s=60.0))
|
|
518
|
+
sender.enqueue(run("a"))
|
|
519
|
+
sender._atexit()
|
|
520
|
+
sender._atexit()
|
|
521
|
+
assert len(s.posts) == 1 and sender.stats()["state"] == "exiting"
|
|
522
|
+
|
|
523
|
+
|
|
524
|
+
def test_enqueue_after_shutdown_is_counted_as_dropped():
|
|
525
|
+
s = Server()
|
|
526
|
+
sender = Sender(s, **fast())
|
|
527
|
+
sender.shutdown()
|
|
528
|
+
sender.enqueue(run("a")); sender.enqueue(run("b"))
|
|
529
|
+
time.sleep(0.1)
|
|
530
|
+
assert s.posts == []
|
|
531
|
+
st = sender.stats()
|
|
532
|
+
assert st["state"] == "stopped" and st["dropped"] == 2 and st["dropped_by_reason"] == {"after_shutdown": 2}
|
|
533
|
+
|
|
534
|
+
|
|
478
535
|
def test_version_matches_the_package():
|
|
479
536
|
import trodo
|
|
480
537
|
from trodo._version import SDK_VERSION
|
|
@@ -490,3 +547,16 @@ def test_feedback_on_a_span_carries_its_span_id():
|
|
|
490
547
|
TrodoClient.feedback(c, "r2", rating=4)
|
|
491
548
|
assert sent[0]["feedback"]["span_id"] == "s9"
|
|
492
549
|
assert "span_id" not in sent[1]["feedback"]
|
|
550
|
+
|
|
551
|
+
|
|
552
|
+
def test_the_exit_flush_takes_the_span_processors_buffer_too():
|
|
553
|
+
from trodo.otel.processor import TrodoSpan
|
|
554
|
+
s = Server()
|
|
555
|
+
sender = Sender(s, **fast(flush_interval_s=60.0))
|
|
556
|
+
p = TrodoSpanProcessor(http_client=None, sender=sender)
|
|
557
|
+
p.enqueue_span(TrodoSpan(span_id="s1", run_id="unfinished", parent_span_id=None, kind="llm", name="x"))
|
|
558
|
+
sender._atexit()
|
|
559
|
+
assert len(s.posts) == 1
|
|
560
|
+
body = s.posts[0]["body"]
|
|
561
|
+
assert body["exiting"] is True
|
|
562
|
+
assert body["items"][0]["run_id"] == "unfinished" and body["items"][0]["spans"][0]["span_id"] == "s1"
|
|
@@ -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
|
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
SDK_VERSION = "3.1.0"
|
|
@@ -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.
|
|
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.
|
|
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
|
|
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.
|
|
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.
|
|
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.
|
|
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.
|
|
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.
|
|
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:
|