Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
23 commits
Select commit Hold shift + click to select a range
82b93c3
fix: record tool definitions in the semconv function-tool shape and s…
PabloPardoGarcia Nov 16, 2026
099fe5d
feat: give invoke_runner and other framework entrypoint operations th…
PabloPardoGarcia Nov 16, 2026
5dfcaf6
fix: normalize structured content attributes from third-party spans
PabloPardoGarcia Nov 16, 2026
55a3e7d
feat: honour OTEL_INSTRUMENTATION_GENAI_CAPTURE_CONTENT when RIUS_CAP…
PabloPardoGarcia Nov 16, 2026
faf35b8
fix: size a blob whose content is a complete replacement from the rep…
PabloPardoGarcia Nov 16, 2026
d7920b3
fix: never export a blob's base64 when a structured value cannot be e…
PabloPardoGarcia Nov 16, 2026
6e9ad51
fix: keep unnamed tool calls as text parts and convert Bedrock and Ge…
PabloPardoGarcia Nov 16, 2026
ca0346b
fix: treat a blank capture-content variable as unset and name the val…
PabloPardoGarcia Nov 16, 2026
4260f88
fix: read a replacement's size without int() on long digit runs
PabloPardoGarcia Nov 16, 2026
9d47941
fix: make tool definitions a fixed point and drop MCP tool headers
PabloPardoGarcia Nov 16, 2026
bcc1db8
fix: drop MCP authorization, lift Chat Completions custom tools and t…
PabloPardoGarcia Nov 16, 2026
2ac97ac
fix: drop MCP credentials from a Vercel provider tool's args
PabloPardoGarcia Nov 16, 2026
359fa1c
Merge remote-tracking branch 'origin/pablo/rius-1877-invoke-entrypoin…
PabloPardoGarcia Nov 16, 2026
50b20ef
Merge remote-tracking branch 'origin/pablo/rius-1874-structured-conte…
PabloPardoGarcia Nov 16, 2026
3e5f88c
Merge remote-tracking branch 'origin/pablo/rius-1875-strip-marker-byt…
PabloPardoGarcia Nov 16, 2026
d1601a0
Merge remote-tracking branch 'origin/pablo/rius-1879-semconv-tool-def…
PabloPardoGarcia Nov 16, 2026
a58f523
Merge remote-tracking branch 'origin/pablo/rius-1883-otel-capture-con…
PabloPardoGarcia Nov 16, 2026
a7eec65
fix: sync rius-semconv v1.13.0 and its shared fixtures
PabloPardoGarcia Nov 16, 2026
474962f
test: a released memoryview blob in a structured content value has no…
PabloPardoGarcia Nov 16, 2026
090b0c9
fix: keep a structured blob past the strip budget whole and sized
PabloPardoGarcia Nov 16, 2026
552681d
test: pin that a structured value past the strip budget with no blob …
PabloPardoGarcia Nov 16, 2026
560cd54
refactor: size a blob's bytes with _serde.byte_object_size
PabloPardoGarcia Nov 16, 2026
80ab5f8
docs: describe the replacement, not base64, in the json_text docstring
PabloPardoGarcia Nov 16, 2026
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
14 changes: 13 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -94,7 +94,7 @@ variables:
| `service_version` | `RIUS_SERVICE_VERSION` | none | Sets `service.version` on the resource. Unset leaves it off, so `OTEL_RESOURCE_ATTRIBUTES` can supply it. |
| `disabled` | `RIUS_DISABLED` | `false` | Kill switch. When true, spans are created but never exported. |
| `sample_rate` | `RIUS_SAMPLE_RATE` | `1.0` | Head sampling ratio `0.0`–`1.0` (whole-trace; children follow root). |
| `capture_content` | `RIUS_CAPTURE_CONTENT` | `true` | When false, prompt/response content is stripped at export (metadata still sent). |
| `capture_content` | `RIUS_CAPTURE_CONTENT` | `true` | When false, prompt/response content is stripped at export (metadata still sent). When `RIUS_CAPTURE_CONTENT` is unset, `OTEL_INSTRUMENTATION_GENAI_CAPTURE_CONTENT` is read (see below). |
| `bridge_foreign_provider` | `RIUS_BRIDGE_FOREIGN_PROVIDER` | `false` | Also export the spans of another OpenTelemetry SDK that owns the global provider (see below). |
| `agent_name` | `RIUS_AGENT_NAME` | `service_name` | The agent this process is. Also the `gen_ai.main_agent.id` when `main_agent_id` is unset, so renaming it changes that id. |
| `main_agent_id` | `RIUS_MAIN_AGENT_ID` | a `gen_ai.main_agent.id` in `OTEL_RESOURCE_ATTRIBUTES`, else the agent name | A stable id for the agent (a registry id or an ARN), stamped as `gen_ai.main_agent.id`. Never a per-process value. |
Expand Down Expand Up @@ -149,6 +149,18 @@ rius.init(mask=lambda value, *, key: hash_pii(value) if "input" in key else valu
rius.init(capture_content=False) # drop content entirely, keep metadata
```

Content capture also follows the OpenTelemetry GenAI setting
`OTEL_INSTRUMENTATION_GENAI_CAPTURE_CONTENT` when `RIUS_CAPTURE_CONTENT` is
unset. `NO_CONTENT` turns capture off, and so does `EVENT_ONLY`, because Rius
records content on spans. `SPAN_ONLY` and `SPAN_AND_EVENT` keep it on. The value
is case-insensitive. An unrecognised one keeps capture on and logs a warning
naming the valid values (the OpenTelemetry conventions fall back to
`NO_CONTENT` instead). An empty value of either variable counts as unset (an
empty `RIUS_CAPTURE_CONTENT` also logs a warning).
The `capture_content` argument wins over both variables, and
`RIUS_CAPTURE_CONTENT` wins over the OpenTelemetry one. With neither set,
capture is on, unlike the OpenTelemetry default of `NO_CONTENT`.

### Sessions, users and workspaces

Three context managers scope every span started inside them, including the
Expand Down
51 changes: 43 additions & 8 deletions src/rius/_media.py
Original file line number Diff line number Diff line change
Expand Up @@ -239,20 +239,45 @@ def replacement(mime: str | None, byte_size: int | None) -> str:
_REPLACEMENT_BETWEEN, _REPLACEMENT_TAIL = _rest.split("<byte_size>")


def is_replacement(value: str) -> bool:
"""Already a complete replacement: never stripped again, never context.
#: 2^53 - 1 has 16 digits, so a run with more significant digits is past it.
_MAX_BYTE_SIZE_DIGITS = 16

The format with a mime that is unknown or token/token and a byte_size of
ASCII digits or unknown; anything that only looks like one is a token.

def parse_replacement(value: str) -> tuple[str | None, int | None] | None:
"""The mime and byte_size a complete replacement names, each None when
unknown; None when ``value`` is no complete replacement (see
``is_replacement``).

The byte_size is the digit run read as a decimal number, leading zeros of
any length allowed. A run with more significant digits than 2^53 - 1 has
is None and is never converted: ``int()`` refuses a string over 4300
digits, and this runs inside the export chain. The caller still bounds a
shorter one to 2^53 - 1, as for a byte_size the part has.
"""
head, between, tail = _REPLACEMENT_HEAD, _REPLACEMENT_BETWEEN, _REPLACEMENT_TAIL
if len(value) < len(head) + len(between) + len(tail):
return False
return None
if not (value.startswith(head) and value.endswith(tail)):
return False
return None
mime, sep, size = value[len(head) : len(value) - len(tail)].rpartition(between)
digits = bool(size) and all("0" <= ch <= "9" for ch in size)
return bool(sep) and (mime == UNKNOWN or is_mime(mime)) and (digits or size == UNKNOWN)
if not (sep and (mime == UNKNOWN or is_mime(mime)) and (digits or size == UNKNOWN)):
return None
byte_size = None
if digits:
significant = size.lstrip("0") or "0"
if len(significant) <= _MAX_BYTE_SIZE_DIGITS:
byte_size = int(significant)
return (None if mime == UNKNOWN else mime), byte_size


def is_replacement(value: str) -> bool:
"""Already a complete replacement: never stripped again, never context.

The format with a mime that is unknown or token/token and a byte_size of
ASCII digits or unknown; anything that only looks like one is a token.
"""
return parse_replacement(value) is not None


# --- the strip ---------------------------------------------------------------
Expand Down Expand Up @@ -1445,7 +1470,9 @@ def native_part(part: Part) -> Part | None:

* A blob carrying content becomes a stripped blob: sized from it,
``not_captured``, its modality from its MIME type first (some producers
label every file an image), else the one it has, else document.
label every file an image), else the one it has, else document. Content
that is a complete replacement gives its size, and its mime when the
part has no valid MIME type.
* Any other part keeps a modality it has, else takes one from its MIME
type, else (a uri) from its filename extension, else document. A blob
without content keeps a valid size and stripped_reason.
Expand All @@ -1457,6 +1484,14 @@ def native_part(part: Part) -> Part | None:
part_type = part.get("type")
mime = part.get("mime_type")
if part_type == "blob" and isinstance(part.get("content"), str):
replaced = parse_replacement(part["content"])
if replaced is not None:
# Bytes a strip already measured (an OTLP bytes value, a byte
# object): the size the base64 of the same bytes would give, and
# the part's own MIME type before the replacement's.
replaced_mime, size = replaced
kept = mime if is_mime(mime) else replaced_mime
return blob_part(own or "document", kept, safe_size(size), NOT_CAPTURED)
return base64_blob(part["content"], own or "document", mime)
if part_type == "uri" and is_data_url(part.get("uri")):
return data_url_blob(part["uri"], own or "document", mime)
Expand Down
118 changes: 110 additions & 8 deletions 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.13.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 @@ -186,6 +186,7 @@

# OTel GenAI (subset we emit)
GEN_AI_OPERATION_NAME = "gen_ai.operation.name"
GEN_AI_OPERATION_NAME_COMPACTION = "compaction"
GEN_AI_PROVIDER_NAME = "gen_ai.provider.name"
GEN_AI_REQUEST_MODEL = "gen_ai.request.model"
GEN_AI_REQUEST_REASONING_LEVEL = "gen_ai.request.reasoning.level"
Expand Down Expand Up @@ -340,9 +341,17 @@
# A free string, not an enum, in the registry.
GEN_AI_TOOL_TYPE = "gen_ai.tool.type"

# The request's tool/function definitions, serialized verbatim (provider
# shapes differ; the backend reads names and sizes from either). Content,
# not identity, so it is listed in CONTENT_ATTRIBUTES.
# The request's tool/function definitions, in the conventions' shape
# where the SDKs recognise the provider's spelling: a function tool
# (OpenAI, Anthropic, Bedrock toolSpec, Gemini function declarations,
# the Vercel AI SDK) becomes {type: function, name, description,
# parameters}, and a provider's built-in tool keeps its fields with its
# type prefixed by the provider name. A built-in tool without a name
# (OpenAI's web_search, Gemini's google_search) stays without one on
# purpose: an invented name would read as a tool that was offered and
# never called. A definition in a shape the SDKs do not recognise is
# recorded as given. Content, not identity, so it is listed in
# CONTENT_ATTRIBUTES.
GEN_AI_TOOL_DEFINITIONS = "gen_ai.tool.definitions"

# The arguments the model passed to the tool. The TypeScript SDK writes it
Expand Down Expand Up @@ -610,6 +619,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 +689,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 @@ -1466,10 +1551,17 @@ class SpanKind(str, Enum):
# are LLM calls the same way chat is, and create_agent is an AGENT span
# just as invoke_agent is, so the mapping is many-to-one and only the
# chat/invoke_agent entries round-trip.
# - CHAIN has no operation of its own, but four operations land on it.
# invoke_workflow and plan are real GenAI operations with no taxonomy
# value of their own; CHAIN is the honest home for both, and the reverse
# direction is the only one that can say so. agent_step is not a
# - CHAIN has no operation of its own, but five operations land on it.
# invoke_workflow, invoke_runner and plan are real GenAI operations with
# no taxonomy value of their own; CHAIN is the honest home for all three,
# and the reverse direction is the only one that can say so.
# invoke_runner is a framework entrypoint (the call that starts a
# framework's run loop), which the conventions define as not being an
# agent, so CHAIN rather than AGENT. The conventions name entrypoint
# operations invoke_{framework_entrypoint} in general, so a table cannot
# list them all: every consumer maps an operation that starts with
# invoke_ and is not in this table to CHAIN as well. invoke_agent is in
# the table, so it keeps AGENT. agent_step is not a
# conventions operation: the Vercel AI SDK's @ai-sdk/otel writes it on
# each step of an agent run (one model call and the tools it asked
# for), a step within the run rather than an agent invocation, so
Expand Down Expand Up @@ -1500,6 +1592,7 @@ class SpanKind(str, Enum):
"retrieval": SpanKind.RETRIEVER,
"rerank": SpanKind.RERANKER,
"invoke_workflow": SpanKind.CHAIN,
"invoke_runner": SpanKind.CHAIN,
"plan": SpanKind.CHAIN,
"agent_step": SpanKind.CHAIN,
"compaction": SpanKind.CHAIN,
Expand Down Expand Up @@ -1613,6 +1706,7 @@ class SpanKind(str, Enum):
"GEN_AI_MAIN_AGENT_ID",
"GEN_AI_MAIN_AGENT_NAME",
"GEN_AI_OPERATION_NAME",
"GEN_AI_OPERATION_NAME_COMPACTION",
"GEN_AI_OUTPUT_MESSAGES",
"GEN_AI_OUTPUT_TYPE",
"GEN_AI_PROVIDER_NAME",
Expand Down Expand Up @@ -1741,6 +1835,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
53 changes: 48 additions & 5 deletions src/rius/_serde.py
Original file line number Diff line number Diff line change
Expand Up @@ -349,21 +349,64 @@ def serialize(value: Any) -> str:
return f"<unserializable {type(value).__name__}>"


def _bounded_dumps(value: Any) -> str:
def json_text(value: Any) -> str:
"""``value`` as JSON text in the one encoding, neither stripped nor cut.

For a value another instrumentation set structured where the conventions
also allow its JSON text: the text is then read and stripped exactly as
that string would be. So it is encoded whole, neither cut at the attribute
cap, where ``serialize`` would, nor at the strip budget: the text is the
very string the JSON form of the value is, and every pass after this one
treats the two alike (a blob's base64 past the budget is rebuilt and
stripped, as it is in that string). The value is already whole in memory
on the span, as that string would be. Never raises: a value the encoder
refuses (a cycle, a key that is no string or number) is its repr, its
byte objects markers, for the strip to read. A caller that writes a byte
object as its replacement before encoding uses :func:`strict_json_text`
and falls back to this on the value as it came.
"""
text = strict_json_text(value)
if text is not None:
return text
try:
return safe_repr(value)
except Exception:
return f"<unserializable {type(value).__name__}>"


def strict_json_text(value: Any) -> str | None:
"""``value`` as JSON text as :func:`json_text` writes it, or None when the
encoder refuses it (a cycle, a key that is no string or number)."""
try:
return _dumps(value, _encode_whole)
except Exception:
return None


def _bounded_dumps(value: Any, finish: Callable[[str], str] = truncate) -> str:
return _dumps(value, lambda plain: _encode_within_budget(plain, finish))


def _dumps(value: Any, encode: Callable[[Any], str]) -> str:
# A lone non-finite number is its name, as the TypeScript SDK writes a
# number with String(); inside a value it is null (see _finite).
if isinstance(value, float) and not math.isfinite(value):
return _non_finite_name(value)
try:
return _encode_within_budget(value)
return encode(value)
except ValueError:
# The encoder refuses NaN and the infinities (allow_nan=False). Only
# then is the value walked to replace them; a cycle raises again and
# serialize falls back to repr, as it always has.
return _encode_within_budget(_finite(value))
return encode(_finite(value))


def _encode_whole(value: Any) -> str:
# The same text the budgeted walk renders, by the C encoder in one pass.
return LONE_SURROGATE.sub(_escape_surrogate, _encoder.encode(value))


def _encode_within_budget(value: Any) -> str:
def _encode_within_budget(value: Any, finish: Callable[[str], str]) -> str:
# iterencode without _one_shot takes the pure-Python path, which yields
# chunks lazily as it walks the value; the C encoder renders everything
# first. A small payload costs a few extra microseconds this way; a large
Expand All @@ -386,4 +429,4 @@ def _encode_within_budget(value: Any) -> str:
if size > MAX_STRIP_CHARS:
kept = "".join(chunks)[:MAX_ATTR_CHARS]
return _cut_past_budget(LONE_SURROGATE.sub(_escape_surrogate, kept))
return truncate("".join(chunks))
return finish("".join(chunks))
Loading
Loading