Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
86 changes: 85 additions & 1 deletion src/rius/_semconv_generated.py
Original file line number Diff line number Diff line change
@@ -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.

Expand Down Expand Up @@ -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
Expand All @@ -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
Expand Down Expand Up @@ -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",
Expand Down
5 changes: 4 additions & 1 deletion src/rius/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down
41 changes: 40 additions & 1 deletion src/rius/heartbeat.py
Original file line number Diff line number Diff line change
Expand Up @@ -99,14 +99,21 @@ 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:
return
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:
Expand All @@ -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:
Expand Down Expand Up @@ -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.
Expand Down
61 changes: 57 additions & 4 deletions src/rius/hints.py
Original file line number Diff line number Diff line change
Expand Up @@ -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__)

Expand Down Expand Up @@ -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:
Expand Down Expand Up @@ -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()

Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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()
Expand Down Expand Up @@ -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
Loading
Loading