diff --git a/src/rius/_semconv_generated.py b/src/rius/_semconv_generated.py index ac321dd..3f50c75 100644 --- a/src/rius/_semconv_generated.py +++ b/src/rius/_semconv_generated.py @@ -1,4 +1,4 @@ -# Vendored from rius-semconv v1.10.0 out/python/_semconv_generated.py by +# Vendored from rius-semconv v1.11.0 out/python/_semconv_generated.py by # scripts/sync-semconv.sh. Do not edit: change the registry in rius-semconv. """Rius semantic conventions: the constants and tables, generated. @@ -610,6 +610,53 @@ # the OpenTelemetry naming rules do not allow for an attribute. RIUS_COMPACTION_SUMMARY_TEXT = "rius.compaction.summary.text" +# --- Agent hints --- +# A hint is a short note Rius sends to a running agent about a problem it +# detected in the agent's current run ("search_docs has returned 0 results +# 5 times in this run; lookup_index covers the same pages"). The SDK +# receives it on the heartbeat response and hands it to the agent: the +# agent's code pulls it, an on_hint callback receives it, or a framework +# hook adds it to the next model call. The rius.hint.* keys are the +# attributes of the rius.hint.delivered event the SDK records at that +# moment, and are never set on a span. No convention defines a hint or +# its delivery. +# The hint's id exactly as Rius sent it, the same on every redelivery. It +# is the join key to the record Rius keeps for each hint it writes, which +# holds the run the hint is about, its code, the text the agent received +# and when it was written, so a reader finds what the hint said and how +# long it took to arrive without the event repeating any of it. +# The SDK de-duplicates on the id, so a hint Rius sends again gives no +# second event on the same channel. A hint can reach the agent through +# more than one channel and gives one event for each: at most one per +# (rius.hint.id, rius.hint.channel). A count of hints delivered must +# deduplicate on rius.hint.id. +RIUS_HINT_ID = "rius.hint.id" + +# Which problem the hint is about, as Rius named it. Copied from the hint +# so that measuring whether hints help can group deliveries by detector +# straight from the trace. The SDK copies it and never interprets it. +# Not gen_ai.prompt.name: a hint is not a managed prompt, and the model +# call a hint is injected into may carry the agent's own +# gen_ai.prompt.name and gen_ai.prompt.version, naming that call's prompt. +RIUS_HINT_CODE = "rius.hint.code" + +# Each code's wording is versioned, and a change of wording bumps the +# version, so two wordings of the same hint can be compared. An int, as +# Rius sends it. Not gen_ai.prompt.version, for the reason given on +# rius.hint.code. +RIUS_HINT_TEMPLATE_VERSION = "rius.hint.template_version" + +# drain when the agent's own code pulled the hint (drain_hints()), +# callback when the SDK passed it to an on_hint callback, inject when a +# framework hook added it to a model call just before the call. Only +# inject guarantees the model saw the hint; with drain and callback the +# agent's code decides what to do with it. Measuring whether hints help +# needs to tell the two apart. +RIUS_HINT_CHANNEL = "rius.hint.channel" +RIUS_HINT_CHANNEL_DRAIN = "drain" +RIUS_HINT_CHANNEL_CALLBACK = "callback" +RIUS_HINT_CHANNEL_INJECT = "inject" + # --- Span event names --- # Deprecated: replaced by the gen_ai.response.time_to_first_chunk span attribute. # First streamed token/chunk arrived. The standard signal is the span @@ -633,6 +680,35 @@ # compacted context sets gen_ai.conversation.compacted. RIUS_COMPACTION_EVENT = "rius.compaction" +# Recorded when the SDK hands a hint to the agent: drain_hints() returns +# it, an on_hint callback receives it, or a framework hook adds it to a +# model call. For every channel, the event goes on the root span of the +# run the hint is about (the hint's trace_id). The SDK keeps each run's +# root span while the run is open, and Rius delivers a hint only while +# its run is open. A hint with no trace_id is about the instance as a +# whole: its event goes on the current span if one is recording, and +# otherwise no event is recorded. +# One run can get several hints, so its root span can carry several of +# these events, one per hint and channel: at most one per +# (rius.hint.id, rius.hint.channel). A count of hints delivered must +# deduplicate on rius.hint.id. +# It carries the rius.hint.* attributes and never the hint's text, which +# the record Rius keeps for each hint it writes holds under the id. +# It records delivery, not the acknowledgement on the heartbeat: an ack +# only tells Rius to stop sending the hint, and the SDK acks hints it +# drops as well. +# For inject, nothing else is needed to measure whether a hint helped. The +# hint's run is the trace the event sits in, and the model calls after the +# hint are the LLM spans of that trace that start after the event's +# timestamp. The hint's id joins the event to the record Rius keeps for each +# hint it writes (its code, its run, when it was written). A key on each +# later model call naming the hints it carried would repeat what that join +# gives. With drain or callback, this event only says the agent's code +# received the hint: the SDK cannot know whether the code passed it to the +# model, acted on it itself, or ignored it, so measuring those needs a +# record from the agent's code. +RIUS_HINT_DELIVERED_EVENT = "rius.hint.delivered" + # --- Pending (partial) spans --- # Marks the content-free snapshot exported at span START; the backend maps it # to Finished=0 and the real span replaces it at end. This key knowingly bends @@ -1741,6 +1817,14 @@ class SpanKind(str, Enum): "RIUS_COMPACTION_TRIGGER_AUTO", "RIUS_COMPACTION_TRIGGER_MANUAL", "RIUS_CONTEXT_SIZES", + "RIUS_HINT_CHANNEL", + "RIUS_HINT_CHANNEL_CALLBACK", + "RIUS_HINT_CHANNEL_DRAIN", + "RIUS_HINT_CHANNEL_INJECT", + "RIUS_HINT_CODE", + "RIUS_HINT_DELIVERED_EVENT", + "RIUS_HINT_ID", + "RIUS_HINT_TEMPLATE_VERSION", "RIUS_MAIN_AGENT_DESCRIPTION", "RIUS_MAIN_AGENT_ID", "RIUS_MAIN_AGENT_NAME", diff --git a/src/rius/client.py b/src/rius/client.py index 935c590..1fd1e34 100644 --- a/src/rius/client.py +++ b/src/rius/client.py @@ -923,7 +923,10 @@ def _do_init( pipeline.add_span_processor(tracker) if config.hints and heartbeat_transport is None: inbox = HintInbox( - tracker.open_trace_ids, per_trace=config.hints_per_trace, on_hint=on_hint + tracker.open_trace_ids, + per_trace=config.hints_per_trace, + on_hint=on_hint, + root_span=tracker.root_span, ) sender = HeartbeatSender( url=config.heartbeat_endpoint, diff --git a/src/rius/heartbeat.py b/src/rius/heartbeat.py index fb9c673..e7c9bee 100644 --- a/src/rius/heartbeat.py +++ b/src/rius/heartbeat.py @@ -99,6 +99,10 @@ def __init__(self) -> None: # trace_id (32-hex) -> count of open root spans in that trace (a # trace id normally has one root, but be safe about duplicates). self._open: dict[str, int] = {} + # trace_id -> its open root spans, oldest first, so a hint's delivery + # can be recorded on its run's root. Dropped when the root ends. Weak: + # a root that is never ended must not keep the whole span alive. + self._roots: dict[str, list[weakref.ref[Span]]] = {} def on_start(self, span: Span, parent_context: Context | None = None) -> None: if span.parent is not None: @@ -106,7 +110,10 @@ def on_start(self, span: Span, parent_context: Context | None = None) -> None: context = span.get_span_context() if context is None: return - self._on_root_start(format(context.trace_id, "032x")) + trace_id = format(context.trace_id, "032x") + with self._lock: + self._open[trace_id] = self._open.get(trace_id, 0) + 1 + self._roots.setdefault(trace_id, []).append(weakref.ref(span)) def on_end(self, span: ReadableSpan) -> None: if span.parent is not None: @@ -121,6 +128,36 @@ def on_end(self, span: ReadableSpan) -> None: self._open.pop(trace_id, None) else: self._open[trace_id] = count + # on_end gets a read-only snapshot, not the started span: match by id. + roots = [ + ref + for ref in self._roots.get(trace_id, []) + if (root := ref()) is not None + and root.get_span_context().span_id != context.span_id + ] + if roots: + self._roots[trace_id] = roots + else: + self._roots.pop(trace_id, None) + + def root_span(self, trace_id: str) -> Span | None: + """The oldest open root span of ``trace_id``, or ``None`` once none is open.""" + with self._lock: + for ref in self._roots.get(trace_id.lower(), []): + root = ref() + if root is not None: + return root + return None + + def reset(self) -> None: + """Forget every open run: a forked child's runs are not its parent's. + + The lock is replaced, not taken: another parent thread may have held it + at the fork, and it would never be released in the child. + """ + self._lock = threading.Lock() + self._open = {} + self._roots = {} def _on_root_start(self, trace_id: str) -> None: with self._lock: @@ -322,6 +359,8 @@ def _reset_in_child(self) -> None: # pragma: no cover — fork-only path self._instance_id = str(uuid.uuid4()) else: self._instance_id, self._secret = mint_instance_identity() + # The parent's open runs have no threads in the child and never end. + self._tracker.reset() if self._hints is not None: # The queue, the pending acks and the ids seen were the parent # instance's; the child is a new instance. diff --git a/src/rius/hints.py b/src/rius/hints.py index c76bbdb..0560967 100644 --- a/src/rius/hints.py +++ b/src/rius/hints.py @@ -36,6 +36,15 @@ from opentelemetry import trace from .config import DEFAULT_HINTS_PER_TRACE +from .semconv import ( + RIUS_HINT_CHANNEL, + RIUS_HINT_CHANNEL_CALLBACK, + RIUS_HINT_CHANNEL_DRAIN, + RIUS_HINT_CODE, + RIUS_HINT_DELIVERED_EVENT, + RIUS_HINT_ID, + RIUS_HINT_TEMPLATE_VERSION, +) logger = logging.getLogger(__name__) @@ -102,6 +111,41 @@ def current_trace_id() -> str | None: return format(context.trace_id, "032x") +RootSpanLookup = Callable[[str], "trace.Span | None"] + + +def _no_root_span(trace_id: str) -> trace.Span | None: + return None + + +def record_delivery(hint: Hint, channel: str, root_span: RootSpanLookup) -> None: + """Record ``rius.hint.delivered`` for a hint the SDK has just handed over. + + The event goes on the root span of the hint's run while that run is open. + A hint with no run goes on the current span of the thread handing it over, + so an instance-wide hint given to ``on_hint`` (on its own thread, with no + current span) records nothing. Carries the hint's identity, never its text. + Never raises. + """ + try: + run = hint.trace_id + span = root_span(run) if run is not None else trace.get_current_span() + # A root that ended a moment ago, before the tracker saw it end. + if span is None or not span.is_recording(): + return + span.add_event( + RIUS_HINT_DELIVERED_EVENT, + { + RIUS_HINT_ID: hint.id, + RIUS_HINT_CODE: hint.code, + RIUS_HINT_TEMPLATE_VERSION: hint.template_version, + RIUS_HINT_CHANNEL: channel, + }, + ) + except Exception as exc: # noqa: BLE001 — recording a delivery never breaks one + logger.debug("rius hints: could not record the delivery of %s: %s", hint.id, exc) + + def parse_response(body: bytes | None) -> list[Any]: """The raw ``hints`` list of a response body, or ``[]`` for "no hints".""" if not body or len(body) > MAX_RESPONSE_BYTES: @@ -168,9 +212,15 @@ class _CallbackWorker: it, so it never holds up shutdown. """ - def __init__(self, callback: Callable[[Hint], object], max_pending: int) -> None: + def __init__( + self, + callback: Callable[[Hint], object], + max_pending: int, + root_span: RootSpanLookup = _no_root_span, + ) -> None: self._callback = callback self._max_pending = max_pending + self._root_span = root_span self._warned = False self._fresh() @@ -209,6 +259,7 @@ def _run(self) -> None: self._call(hint) def _call(self, hint: Hint) -> None: + record_delivery(hint, RIUS_HINT_CHANNEL_CALLBACK, self._root_span) try: self._callback(hint) except BaseException as exc: # noqa: BLE001 — SystemExit must not end the worker @@ -251,12 +302,14 @@ def __init__( on_hint: Callable[[Hint], object] | None = None, verify: Callable[[Mapping[str, Any]], bool] = verify_hint, max_pending_callbacks: int = _MAX_PENDING_CALLBACKS, + root_span: RootSpanLookup = _no_root_span, ) -> None: self._open_traces = open_traces self._per_trace = per_trace self._max_queued = max_queued + self._root_span = root_span self._callbacks = ( - None if on_hint is None else _CallbackWorker(on_hint, max_pending_callbacks) + None if on_hint is None else _CallbackWorker(on_hint, max_pending_callbacks, root_span) ) self._verify = verify self._lock = threading.Lock() @@ -396,6 +449,6 @@ def drain(self, trace_id: str | None) -> list[Hint]: for hint in self._queue: (drained if hint.trace_id in (None, wanted) else kept).append(hint) self._queue = kept - # This is where a hint is handed to the agent: the place to record its - # delivery on the current span once the semantic conventions name it. + for hint in drained: + record_delivery(hint, RIUS_HINT_CHANNEL_DRAIN, self._root_span) return drained diff --git a/tests/test_hints.py b/tests/test_hints.py index 5e3b330..5f800f2 100644 --- a/tests/test_hints.py +++ b/tests/test_hints.py @@ -795,13 +795,13 @@ def drain(into: list[Hint]) -> None: def _hint_client(endpoint: _Endpoint, **kwargs: Any) -> rius.GlassflowClient: + kwargs.setdefault("span_exporter", InMemorySpanExporter()) return init( service_name="svc", api_key="k", endpoint=endpoint.base_url, heartbeat=True, heartbeat_interval=300.0, - span_exporter=InMemorySpanExporter(), **kwargs, ) @@ -956,3 +956,195 @@ def test_a_second_client_keeps_its_own_hints(endpoint: _Endpoint) -> None: def test_hint_names_are_public() -> None: assert "Hint" in rius.__all__ assert "drain_hints" in rius.__all__ + + +# --------------------------------------------------------------------------- +# Delivery events: rius.hint.delivered on the run's root span +# --------------------------------------------------------------------------- + + +def _delivered(exporter: InMemorySpanExporter, span_name: str) -> list[dict[str, Any]]: + (span,) = [s for s in exporter.get_finished_spans() if s.name == span_name] + return [dict(e.attributes or {}) for e in span.events if e.name == "rius.hint.delivered"] + + +def _ping(client: rius.GlassflowClient) -> None: + assert client._heartbeat is not None # noqa: SLF001 + client._heartbeat._send_ping() # noqa: SLF001 + + +def test_draining_a_hint_records_its_delivery_on_the_runs_root_span(endpoint: _Endpoint) -> None: + exporter = InMemorySpanExporter() + client = _hint_client(endpoint, set_global=False, hints=True, span_exporter=exporter) + try: + endpoint.wait_for(1) + tracer = client.get_tracer() + with tracer.start_as_current_span("run") as run: + this_trace = format(run.get_span_context().trace_id, "032x") + endpoint.reply(200, _body(_wire_hint(1, this_trace))) + _ping(client) + with tracer.start_as_current_span("model call"): + assert _ids(client.drain_hints()) == [_hint_id(1)] + finally: + client.shutdown() + assert _delivered(exporter, "run") == [ + { + "rius.hint.id": _hint_id(1), + "rius.hint.code": "CF-01", + "rius.hint.template_version": 1, + "rius.hint.channel": "drain", + } + ] + assert _delivered(exporter, "model call") == [] + + +def test_on_hint_records_a_callback_delivery_and_drain_a_second_one(endpoint: _Endpoint) -> None: + exporter = InMemorySpanExporter() + received: list[Hint] = [] + client = _hint_client( + endpoint, set_global=False, hints=True, on_hint=received.append, span_exporter=exporter + ) + try: + endpoint.wait_for(1) + with client.get_tracer().start_as_current_span("run") as run: + this_trace = format(run.get_span_context().trace_id, "032x") + endpoint.reply(200, _body(_wire_hint(1, this_trace))) + _ping(client) + assert _eventually(lambda: len(received) == 1) + endpoint.reply(200, _body(_wire_hint(1, this_trace))) # a redelivery + _ping(client) + assert _ids(client.drain_hints()) == [_hint_id(1)] + assert client.drain_hints() == [] + finally: + client.shutdown() + channels = [event["rius.hint.channel"] for event in _delivered(exporter, "run")] + assert sorted(channels) == ["callback", "drain"] + + +def test_a_delivery_event_never_carries_the_hints_text(endpoint: _Endpoint) -> None: + exporter = InMemorySpanExporter() + client = _hint_client(endpoint, set_global=False, hints=True, span_exporter=exporter) + try: + endpoint.wait_for(1) + with client.get_tracer().start_as_current_span("run") as run: + this_trace = format(run.get_span_context().trace_id, "032x") + endpoint.reply(200, _body(_wire_hint(1, this_trace, text="secret advice"))) + _ping(client) + client.drain_hints() + finally: + client.shutdown() + (event,) = _delivered(exporter, "run") + assert "secret advice" not in json.dumps(event) + + +def test_an_instance_wide_hint_is_recorded_on_the_current_span_or_not_at_all( + endpoint: _Endpoint, +) -> None: + exporter = InMemorySpanExporter() + client = _hint_client(endpoint, set_global=False, hints=True, span_exporter=exporter) + try: + endpoint.wait_for(1) + endpoint.reply(200, _body(_wire_hint(1), _wire_hint(2))) + _ping(client) + tracer = client.get_tracer() + with tracer.start_as_current_span("run"), tracer.start_as_current_span("step"): + assert _ids(client.drain_hints()) == [_hint_id(1), _hint_id(2)] + endpoint.reply(200, _body(_wire_hint(3))) + _ping(client) + assert _ids(client.drain_hints()) == [_hint_id(3)] # outside any span: no event + finally: + client.shutdown() + assert [e["rius.hint.id"] for e in _delivered(exporter, "step")] == [_hint_id(1), _hint_id(2)] + assert _delivered(exporter, "run") == [] + + +def test_draining_a_finished_runs_hint_records_nothing_and_still_returns_it( + endpoint: _Endpoint, +) -> None: + exporter = InMemorySpanExporter() + client = _hint_client(endpoint, set_global=False, hints=True, span_exporter=exporter) + try: + endpoint.wait_for(1) + run = client.get_tracer().start_span("run") + this_trace = format(run.get_span_context().trace_id, "032x") + endpoint.reply(200, _body(_wire_hint(1, this_trace))) + _ping(client) + run.end() + assert _ids(client.drain_hints(trace_id=this_trace)) == [_hint_id(1)] + finally: + client.shutdown() + assert _delivered(exporter, "run") == [] + + +def test_the_tracker_returns_a_runs_open_root_span_until_it_ends() -> None: + exporter = InMemorySpanExporter() + client = init(set_global=False, service_name="svc", heartbeat=False, span_exporter=exporter) + tracker = OpenRootSpanTracker() + client._provider.add_span_processor(tracker) # noqa: SLF001 — test wiring + try: + tracer = client.get_tracer() + with tracer.start_as_current_span("run") as run: + trace_id = format(run.get_span_context().trace_id, "032x") + with tracer.start_as_current_span("child"): + assert tracker.root_span(trace_id) is run + assert tracker.root_span(trace_id) is None + assert tracker.root_span(TRACE_A) is None + finally: + client.shutdown() + + +def test_a_root_span_that_never_ends_is_not_kept_alive_by_the_tracker() -> None: + import gc + + client = init( + set_global=False, service_name="svc", heartbeat=False, span_exporter=InMemorySpanExporter() + ) + tracker = OpenRootSpanTracker() + client._provider.add_span_processor(tracker) # noqa: SLF001 — test wiring + try: + abandoned = client.get_tracer().start_span("run") # never ended + trace_id = format(abandoned.get_span_context().trace_id, "032x") + assert tracker.root_span(trace_id) is abandoned + del abandoned + gc.collect() + assert tracker.root_span(trace_id) is None + finally: + client.shutdown() + + +def test_a_forked_child_forgets_the_parents_open_runs(endpoint: _Endpoint) -> None: + client = init( + set_global=False, service_name="svc", heartbeat=False, span_exporter=InMemorySpanExporter() + ) + tracker = OpenRootSpanTracker() + client._provider.add_span_processor(tracker) # noqa: SLF001 — test wiring + sender = _sender(endpoint, inbox=_inbox(tracker), tracker=tracker) + run = client.get_tracer().start_span("run") + trace_id = format(run.get_span_context().trace_id, "032x") + try: + assert tracker.open_trace_ids() == [trace_id] + sender._reset_in_child() # noqa: SLF001 — what the fork hook runs in the child + assert tracker.open_trace_ids() == [] + assert tracker.root_span(trace_id) is None + finally: + sender.stop() + run.end() + client.shutdown() + + +def test_a_failing_or_ended_root_span_lookup_never_breaks_a_drain() -> None: + def broken(trace_id: str) -> Any: + raise RuntimeError("lookup failed") + + client = init( + set_global=False, service_name="svc", heartbeat=False, span_exporter=InMemorySpanExporter() + ) + try: + ended = client.get_tracer().start_span("run") + ended.end() + for lookup in (broken, lambda trace_id: ended): + inbox = _inbox(_open(TRACE_A), root_span=lookup) + inbox.accept(_body(_wire_hint(1, TRACE_A))) + assert _ids(inbox.drain(TRACE_A)) == [_hint_id(1)] + finally: + client.shutdown()