diff --git a/src/rius/__init__.py b/src/rius/__init__.py index 72a920e..3781df9 100644 --- a/src/rius/__init__.py +++ b/src/rius/__init__.py @@ -2,11 +2,19 @@ __version__ = "1.5.5" # x-release-please-version -from .client import GlassflowClient, build_span_exporter, get_tracer, init, register_workspace +from .client import ( + GlassflowClient, + build_span_exporter, + drain_hints, + get_tracer, + init, + register_workspace, +) from .compaction import mark_compaction from .config import GlassflowConfig, resolve_config from .export_health import ProbeTransport from .generation import Generation, start_as_current_generation, start_generation +from .hints import Hint from .observe import observe from .semconv import SpanKind from .session import session @@ -18,11 +26,13 @@ "Generation", "GlassflowClient", "GlassflowConfig", + "Hint", "Observation", "ProbeTransport", "SpanKind", "__version__", "build_span_exporter", + "drain_hints", "get_tracer", "init", "mark_compaction", 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 c97f1d0..1fd1e34 100644 --- a/src/rius/client.py +++ b/src/rius/client.py @@ -38,7 +38,8 @@ ResourceAdoptingExporter, bridge, ) -from .heartbeat import HeartbeatSender, OpenRootSpanTracker +from .heartbeat import HeartbeatSender, OpenRootSpanTracker, mint_instance_identity +from .hints import Hint, HintInbox, current_trace_id from .instrumentation import enable_instrumentations, instruments_for from .instrumentation import release as release_instrumentations from .masking import MaskingSpanExporter @@ -222,8 +223,10 @@ def __init__( connectivity_thread: threading.Thread | None = None, routing: RoutingSpanExporter | None = None, bridge: Bridge | None = None, + hints: HintInbox | None = None, ) -> None: self._provider = provider + self._hints = hints self._bridge = bridge self.config = config self._heartbeat = heartbeat @@ -250,6 +253,18 @@ def register_workspace(self, alias: str, api_key: str) -> None: ) self._routing.register(alias, api_key) + def drain_hints(self, trace_id: str | None = None) -> list[Hint]: + """Remove and return the hints received for a run, oldest first. + + Returns the hints for ``trace_id`` (default: the trace of the current + span context) plus the hints about the instance as a whole. Outside + any span, only the instance-wide ones. Always empty when hints are + off (``init(hints=True)`` / ``RIUS_HINTS`` turns them on). + """ + if self._hints is None: + return [] + return self._hints.drain(trace_id if trace_id is not None else current_trace_id()) + def get_tracer(self, name: str = TRACER_NAME) -> trace.Tracer: """Return a tracer bound to this client's provider. @@ -315,6 +330,9 @@ def init( span_exporter: SpanExporter | None = None, heartbeat: bool | None = None, heartbeat_interval: float | None = None, + hints: bool | None = None, + hints_per_trace: int | None = None, + on_hint: Callable[[Hint], object] | None = None, agent_name: str | None = None, main_agent_id: str | None = None, main_agent_description: str | None = None, @@ -389,6 +407,18 @@ def init( heartbeat_interval: Seconds between pings (default 15, clamped to ``[5, 300]``). The server fixes stale at 30s and gone at 60s since the last ping, so keep this well under 30s. + hints: Ask Rius for hints on the heartbeat response (``RIUS_HINTS``; + off by default). A hint is a short note about a problem Rius + detected in one of this process's open runs; read them with + ``drain_hints()``. Needs the heartbeat and its default transport: + with a ``heartbeat_transport`` hints stay off. + hints_per_trace: The most hints accepted for one run + (``RIUS_HINTS_PER_TRACE``, default 3); later ones are dropped. + on_hint: Called once with each newly accepted ``Hint``, on a + dedicated daemon thread, so it can never delay a heartbeat. If it + falls behind, the oldest pending calls are skipped. An exception + it raises is logged, and the hint stays queued for + ``drain_hints()`` either way. agent_name: Identity both heartbeats and spans group under, stamped on the resource as ``gen_ai.main_agent.name`` AND, unchanged, as ``gen_ai.agent.name``; defaults to ``service_name``. The @@ -490,6 +520,9 @@ def init( span_exporter=span_exporter, heartbeat=heartbeat, heartbeat_interval=heartbeat_interval, + hints=hints, + hints_per_trace=hints_per_trace, + on_hint=on_hint, agent_name=agent_name, main_agent_id=main_agent_id, main_agent_description=main_agent_description, @@ -645,6 +678,9 @@ def _do_init( span_exporter: SpanExporter | None, heartbeat: bool | None, heartbeat_interval: float | None, + hints: bool | None, + hints_per_trace: int | None, + on_hint: Callable[[Hint], object] | None, agent_name: str | None, main_agent_id: str | None, main_agent_description: str | None, @@ -671,6 +707,8 @@ def _do_init( capture_content=capture_content, heartbeat=heartbeat, heartbeat_interval=heartbeat_interval, + hints=hints, + hints_per_trace=hints_per_trace, agent_name=agent_name, main_agent_id=main_agent_id, main_agent_description=main_agent_description, @@ -689,7 +727,16 @@ def _do_init( # spans keep this (ancestor) id while its heartbeat re-arms with a fresh # one; deployments needing exact per-worker span identity should init() # after fork. - instance_id = str(uuid.uuid4()) + # Derived from a per-instance secret the heartbeat presents, so another + # holder of the workspace key cannot ping as this instance. A custom + # transport is handed the payload only and could never send the secret, + # so it pings as a legacy instance: liveness as before, never hints. + instance_id: str + instance_secret: str | None + if heartbeat_transport is None: + instance_id, instance_secret = mint_instance_identity() + else: + instance_id, instance_secret = str(uuid.uuid4()), None agent_name = _agent.named_agent(config.agent_name) # telemetry.sdk.* is reserved for the OTel SDK itself (Resource.create fills # it); we identify as a distribution via telemetry.distro.*. @@ -867,18 +914,31 @@ def _do_init( "rius heartbeat not started: no credentials (set api_key or an " "Authorization header in headers)" ) + inbox: HintInbox | None = None + hints_off_because = _why_hints_are_off(config, heartbeat_transport, can_authenticate) + if config.hints and hints_off_because is not None: + logger.warning("rius hints were requested but are off: %s", hints_off_because) if config.heartbeat and not config.disabled and can_authenticate: tracker = OpenRootSpanTracker() 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, + root_span=tracker.root_span, + ) sender = HeartbeatSender( url=config.heartbeat_endpoint, headers=config.headers, interval=config.heartbeat_interval, agent_name=config.agent_name, instance_id=instance_id, + instance_secret=instance_secret, tracker=tracker, transport=heartbeat_transport, foreign_parent_spans=None if detector is None else (lambda: detector.count), + hints=inbox, ) sender.start() @@ -890,12 +950,33 @@ def _do_init( connectivity_thread=connectivity_thread, routing=routing, bridge=bridged, + hints=inbox, ) if set_global: _current_client = client return client +def _why_hints_are_off( + config: GlassflowConfig, + heartbeat_transport: Callable[[dict[str, Any]], None] | None, + can_authenticate: bool, +) -> str | None: + """Why hints cannot run with this configuration, or None when they can.""" + if config.disabled: + return "rius is disabled (the kill switch is on)" + if not config.heartbeat: + return "the heartbeat is off, and hints ride on its response" + if heartbeat_transport is not None: + return ( + "a custom heartbeat_transport is handed the payload only, so it cannot " + "authenticate the instance, and hints are delivered only to authenticated pings" + ) + if not can_authenticate: + return "no credentials (set api_key or an Authorization header), so no heartbeat runs" + return None + + def _foreign_global_name() -> str | None: """``module.Class`` of the global provider when another SDK already set it.""" existing = trace.get_tracer_provider() @@ -952,6 +1033,19 @@ def _register_global( return None +def drain_hints(trace_id: str | None = None) -> list[Hint]: + """Remove and return the global client's hints for a run, oldest first. + + See :meth:`GlassflowClient.drain_hints`. Empty when no global ``init()`` is + active or hints are off. + """ + with _lock: + client = _current_client + if client is None or client._is_shutdown: + return [] + return client.drain_hints(trace_id) + + def get_tracer(name: str = TRACER_NAME) -> trace.Tracer: """Return a tracer bound to the active global client's provider. diff --git a/src/rius/config.py b/src/rius/config.py index a00d1ba..85cbe0e 100644 --- a/src/rius/config.py +++ b/src/rius/config.py @@ -34,6 +34,8 @@ ENV_CAPTURE_CONTENT = "RIUS_CAPTURE_CONTENT" ENV_HEARTBEAT = "RIUS_HEARTBEAT" ENV_HEARTBEAT_INTERVAL = "RIUS_HEARTBEAT_INTERVAL" +ENV_HINTS = "RIUS_HINTS" +ENV_HINTS_PER_TRACE = "RIUS_HINTS_PER_TRACE" ENV_AGENT_NAME = "RIUS_AGENT_NAME" ENV_MAIN_AGENT_ID = "RIUS_MAIN_AGENT_ID" ENV_MAIN_AGENT_DESCRIPTION = "RIUS_MAIN_AGENT_DESCRIPTION" @@ -53,6 +55,9 @@ # Debounce for partial spans: 0 = emit immediately at span start; # N>0 = emit only if the span is still open after N seconds. Beyond 60s a # "live" view stops being live, so larger values are clamped. +# The most hints accepted for one run (trace); later ones are dropped and acked. +DEFAULT_HINTS_PER_TRACE = 3 + PARTIAL_SPANS_DELAY_MIN = 0.0 PARTIAL_SPANS_DELAY_MAX = 60.0 @@ -98,6 +103,17 @@ def _env_float(name: str, *, default: float) -> float: return _finite(name, value, default) +def _env_int(name: str, *, default: int) -> int: + raw = os.getenv(name) + if raw is None: + return default + try: + return int(raw.strip()) + except ValueError: + logger.warning("%s=%r is not an integer; using the default (%s).", name, raw, default) + return default + + def _finite(name: str, value: float, default: float) -> float: """``default`` for NaN and the infinities, which a min/max clamp lets through. @@ -135,6 +151,10 @@ class GlassflowConfig: capture_content: bool = True heartbeat: bool = True heartbeat_interval: float = DEFAULT_HEARTBEAT_INTERVAL + # Opt-in: ask for hints on the heartbeat response (needs the heartbeat + # and its default transport). + hints: bool = False + hints_per_trace: int = DEFAULT_HINTS_PER_TRACE agent_name: str = DEFAULT_SERVICE_NAME # The rest of the main agent's identity: the agent this PROCESS is. Only # the name has an older counterpart (``agent_name``, above, which these @@ -250,6 +270,13 @@ def _clamp_heartbeat_interval(value: float) -> float: return clamped +def _non_negative_hints_per_trace(value: int) -> int: + if value >= 0: + return value + logger.warning("hints_per_trace %s is negative; using 0", value) + return 0 + + def resolve_config( *, endpoint: str | None = None, @@ -270,6 +297,8 @@ def resolve_config( partial_spans_delay: float | None = None, session_id: str | None = None, bridge_foreign_provider: bool | None = None, + hints: bool | None = None, + hints_per_trace: int | None = None, ) -> GlassflowConfig: """Resolve SDK configuration from arguments, environment, then defaults. @@ -355,6 +384,11 @@ def resolve_config( Off by default: rius then exports that SDK's spans, which is consent the caller gives explicitly. Off, rius keeps to its own provider and flags the parents it never receives. + hints: Ask Rius for hints on the heartbeat response (``RIUS_HINTS``). + Off by default. Needs the heartbeat and its default transport. + hints_per_trace: The most hints accepted for one run + (``RIUS_HINTS_PER_TRACE``, default 3); later ones are dropped. A + negative value means 0. Returns: The resolved, immutable ``GlassflowConfig``. @@ -381,6 +415,12 @@ def resolve_config( if heartbeat_interval is None else _finite("heartbeat_interval", heartbeat_interval, DEFAULT_HEARTBEAT_INTERVAL) ) + resolved_hints = _env_bool(ENV_HINTS, default=False) if hints is None else hints + resolved_hints_per_trace = _non_negative_hints_per_trace( + _env_int(ENV_HINTS_PER_TRACE, default=DEFAULT_HINTS_PER_TRACE) + if hints_per_trace is None + else hints_per_trace + ) resolved_agent_name = agent_name or os.getenv(ENV_AGENT_NAME) or resolved_service_name resolved_main_agent_id = main_agent_id or os.getenv(ENV_MAIN_AGENT_ID) or None resolved_main_agent_description = ( @@ -418,6 +458,8 @@ def resolve_config( capture_content=resolved_capture_content, heartbeat=resolved_heartbeat, heartbeat_interval=resolved_heartbeat_interval, + hints=resolved_hints, + hints_per_trace=resolved_hints_per_trace, agent_name=resolved_agent_name, main_agent_id=resolved_main_agent_id, main_agent_description=resolved_main_agent_description, diff --git a/src/rius/heartbeat.py b/src/rius/heartbeat.py index 0c96e97..e7c9bee 100644 --- a/src/rius/heartbeat.py +++ b/src/rius/heartbeat.py @@ -19,14 +19,26 @@ misinformation), and delivery problems warn once per process. - ``fork()``: the child re-arms with a NEW ``instance_id``, so one identity never speaks for two processes. +- The ``instance_id`` is derived from a per-instance secret + (:func:`mint_instance_identity`), and every ping carries that secret in the + ``Rius-Instance-Secret`` header. The receiver checks the derivation, so + another holder of the same workspace key cannot speak for this instance. + The secret is never stored or logged. A forked child mints its own pair. +- Hints (opt-in): with a :class:`~rius.hints.HintInbox`, an authenticated + sender asks for hints with ``accepts``, acks the ones it processed with + ``acked``, and hands each response body to the inbox. The hint path never + fails or delays a ping. """ from __future__ import annotations import atexit +import base64 +import hashlib import json import logging import os +import secrets import threading import urllib.request import uuid @@ -39,6 +51,7 @@ from opentelemetry.sdk.trace import ReadableSpan, Span, SpanProcessor from . import __version__ +from .hints import ACCEPTED_FORMATS, MAX_REQUEST_BYTES, MAX_RESPONSE_BYTES, HintInbox logger = logging.getLogger(__name__) @@ -86,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: @@ -93,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: @@ -108,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: @@ -125,23 +175,79 @@ def force_flush(self, timeout_millis: int = 30_000) -> bool: # pragma: no cover return True -def _http_transport(url: str, headers: dict[str, str]) -> Callable[[dict[str, Any], float], None]: +# Header and size of the per-instance secret; the receiver accepts 32 to 64 +# bytes of unpadded base64url. +INSTANCE_SECRET_HEADER = "Rius-Instance-Secret" +_INSTANCE_SECRET_BYTES = 32 + + +def derive_instance_id(secret: bytes) -> str: + """The instance id a secret certifies: SHA-256's first 16 bytes as a v8 UUID. + + Must match ``heartbeat.DeriveInstanceID`` in argus-core byte for byte. + """ + digest = bytearray(hashlib.sha256(secret).digest()[:16]) + digest[6] = (digest[6] & 0x0F) | 0x80 # version 8 + digest[8] = (digest[8] & 0x3F) | 0x80 # RFC 9562 variant + return str(uuid.UUID(bytes=bytes(digest))) + + +def mint_instance_identity() -> tuple[str, str]: + """A fresh ``(instance_id, secret)`` pair; the id is derived from the secret. + + The secret is 32 random bytes, unpadded base64url, as sent in the header. + """ + raw = secrets.token_bytes(_INSTANCE_SECRET_BYTES) + return derive_instance_id(raw), base64.urlsafe_b64encode(raw).rstrip(b"=").decode() + + +# A transport sends one encoded payload and, when asked to read, returns the +# response body; None when it has none to give (not asked, an injected +# transport, or a body over the read cap). Any non-2xx raises. +_Transport = Callable[[bytes, float, bool], bytes | None] + + +def _encode(payload: dict[str, Any]) -> bytes: + """The request body exactly as sent, so its size can be checked first.""" + return json.dumps(payload).encode("utf-8") + + +def _http_transport( + url: str, headers: dict[str, str], secret: Callable[[], str | None] +) -> _Transport: """Default transport: a plain POST with a per-call timeout, no retries. TLS certificate verification is urllib's default and is deliberately not configurable here: a liveness signal must not become a reason to accept - unverified endpoints. + unverified endpoints. ``secret`` is read per ping because a forked child + replaces it. """ - def send(payload: dict[str, Any], timeout: float) -> None: + # The body is JSON whatever the caller's headers say, and the secret is + # ours: a caller header with either name is dropped, in any letter case. + reserved = {"content-type", INSTANCE_SECRET_HEADER.lower()} + caller_headers = {k: v for k, v in headers.items() if k.lower() not in reserved} + + def send(body: bytes, timeout: float, read: bool) -> bytes | None: + request_headers = {"Content-Type": "application/json", **caller_headers} + current = secret() + if current is not None: + request_headers[INSTANCE_SECRET_HEADER] = current request = urllib.request.Request( url, - data=json.dumps(payload).encode("utf-8"), - headers={"Content-Type": "application/json", **headers}, + data=body, + headers=request_headers, method="POST", ) - with urllib.request.urlopen(request, timeout=timeout): - pass # 2xx is success; the body is ignored by contract + if not read: + with urllib.request.urlopen(request, timeout=timeout): + pass # 2xx is success; the body is not read + return None + with urllib.request.urlopen(request, timeout=timeout) as response: + # 2xx is liveness success. The body (hints) is read up to the cap; + # one byte more tells an over-cap body, which counts as none. + data: bytes = response.read(MAX_RESPONSE_BYTES + 1) + return data if len(data) <= MAX_RESPONSE_BYTES else None return send @@ -158,10 +264,12 @@ def __init__( agent_name: str, instance_id: str, tracker: OpenRootSpanTracker, + instance_secret: str | None = None, transport: Callable[[dict[str, Any]], None] | None = None, ping_timeout: float = _PING_TIMEOUT_S, final_ping_timeout: float = _FINAL_PING_TIMEOUT_S, foreign_parent_spans: Callable[[], int] | None = None, + hints: HintInbox | None = None, ) -> None: self._interval = interval self._foreign_parent_spans = foreign_parent_spans @@ -169,16 +277,32 @@ def __init__( self._tracker = tracker self._ping_timeout = ping_timeout self._final_ping_timeout = final_ping_timeout + self._send_payload: Callable[[dict[str, Any], float, bool], bytes | None] if transport is not None: - # Injected transports (tests) take the payload only. - self._send: Callable[[dict[str, Any], float], None] = lambda p, _t: transport(p) + # Injected transports (tests) take the payload only and return no body. + def send_to_injected(payload: dict[str, Any], _timeout: float, _read: bool) -> None: + transport(payload) + + self._send_payload = send_to_injected else: - self._send = _http_transport(url, headers) + http = _http_transport(url, headers, lambda: self._secret) + self._send_payload = lambda payload, timeout, read: http( + _encode(payload), timeout, read + ) # Injected: the same id rides spans as the service.instance.id # resource attribute, which is what lets the backend join heartbeats # to traces. Only _reset_in_child mints a fresh one (a forked child # is a new process lifetime). self._instance_id = instance_id + # The secret instance_id is derived from (mint_instance_identity); it + # proves this process is the instance. Never persisted, logged or put + # in the payload. None (tests, custom senders) sends no header, which + # the receiver accepts only for ids that are not derived. + self._secret = instance_secret + # Hints are delivered only to an authenticated ping, which needs the + # default transport (it sends the secret) and a derived id. + self._hints = hints if transport is None and instance_secret is not None else None + self._refusal_warned = False self._stop_event = threading.Event() self._stopped = False self._lock = threading.Lock() @@ -219,6 +343,8 @@ def stop(self) -> None: if self._thread is not None: self._thread.join(timeout=self._ping_timeout + 1.0) self._send_ping(stopped=True) + if self._hints is not None: + self._hints.close() # never waits for an on_hint still running def _run(self) -> None: self._send_ping() @@ -228,7 +354,17 @@ def _run(self) -> None: def _reset_in_child(self) -> None: # pragma: no cover — fork-only path if self._stopped: return - self._instance_id = str(uuid.uuid4()) + if self._secret is None: + # A legacy sender stays legacy: it has no way to send a secret. + 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. + self._hints.reset() self._stop_event = threading.Event() self.start() @@ -257,15 +393,65 @@ def _build_payload(self, *, stopped: bool = False) -> dict[str, Any]: if stopped: # Present-and-true only on the final ping; false is never sent. payload["stopped"] = True + if self._hints is not None: + payload["accepts"] = list(ACCEPTED_FORMATS) + payload["acked"] = [] return payload + def _add_acks(self, payload: dict[str, Any]) -> list[str]: + """Put the pending acks in ``payload`` and return the ids it carries. + + Drops the newest ids until the encoded request is within + ``MAX_REQUEST_BYTES``; those wait for a later ping. Never raises: on + any error the ping goes out with no acks. + """ + if self._hints is None: + return [] + try: + acked = self._hints.acks_to_send() + while acked: + payload["acked"] = acked + if len(_encode(payload)) <= MAX_REQUEST_BYTES: + return acked + acked = acked[:-1] + except Exception as exc: # noqa: BLE001 — an ack never costs a ping + logger.debug("rius hints: could not add acks to the heartbeat: %s", exc) + payload["acked"] = [] + return [] + def _send_ping(self, *, stopped: bool = False) -> None: timeout = self._final_ping_timeout if stopped else self._ping_timeout try: - self._send(self._build_payload(stopped=stopped), timeout) + payload = self._build_payload(stopped=stopped) + acked = self._add_acks(payload) + # Only a hints ping reads the body; the stopped one's is ignored. + read = self._hints is not None and not stopped + body = self._send_payload(payload, timeout, read) except Exception as exc: # noqa: BLE001 — never raises into user code - if not self._delivery_warned: - self._delivery_warned = True - logger.warning("heartbeat delivery failed (%s); further failures log at DEBUG", exc) - else: - logger.debug("heartbeat delivery failed: %s", exc) + if self._hints is not None and getattr(exc, "code", None) == 413: + self._hints.request_too_large() + self._delivery_failed(exc) + return + if self._hints is not None: + self._hints.acks_delivered(acked) + if not stopped: + self._hints.accept(body) + + def _delivery_failed(self, exc: Exception) -> None: + if getattr(exc, "code", None) == 403 and not self._refusal_warned: + # The one refusal a user can act on: something rewrote the + # instance id or this header between the SDK and the receiver. + self._refusal_warned = True + logger.warning( + "rius heartbeat refused (403): the receiver did not accept this " + "instance secret for instance_id %s; check that nothing overrides " + "the instance id or strips the %s header", + self._instance_id, + INSTANCE_SECRET_HEADER, + ) + return + if not self._delivery_warned: + self._delivery_warned = True + logger.warning("heartbeat delivery failed (%s); further failures log at DEBUG", exc) + else: + logger.debug("heartbeat delivery failed: %s", exc) diff --git a/src/rius/hints.py b/src/rius/hints.py new file mode 100644 index 0000000..0560967 --- /dev/null +++ b/src/rius/hints.py @@ -0,0 +1,454 @@ +"""Hints received on the heartbeat response. + +A hint is a short note from Rius about a problem it detected in one of this +instance's open runs. It is advice, not a command: the SDK queues it, and the +agent's code drains it at a safe point (typically before its next model call) +and decides what to do with it. + +The heartbeat contract's "Hints" section is normative; this module implements +the SDK side of it: + +- The response body is "no hints" unless it is ``{"format": , "hints": [...]}``. Unknown fields are ignored. +- Every hint the inbox processes is acked, whether it was queued or dropped + (duplicate, failed verification, not one of this process's open traces, + over the per-trace budget, malformed). An ack means "stop sending this". +- ``expires_at`` is never compared with the local clock: expiry is the + receiver's job, and a skewed client clock would drop every hint silently. +- Nothing here raises into the heartbeat ping or into user code. + +All state lives on one :class:`HintInbox` per client, so a scoped client or a +second ``init()`` keeps its own hints. +""" + +from __future__ import annotations + +import json +import logging +import re +import threading +from collections import OrderedDict, deque +from collections.abc import Callable, Mapping, Sequence +from dataclasses import dataclass, field +from types import MappingProxyType +from typing import Any + +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__) + +# The capability strings this SDK sends in ``accepts``; a response in any +# other ``format`` is ignored. +ACCEPTED_FORMATS: tuple[str, ...] = ("hints",) +# The SDK reads at most this much of a response body; a longer one is "no hints". +MAX_RESPONSE_BYTES = 64 * 1024 +# ``acked`` holds at most this many ids, and the encoded request at most this +# many bytes; ids that do not fit are carried to the next ping. +MAX_ACKED_PER_PING = 16 +MAX_REQUEST_BYTES = 3584 + +_SEEN_IDS = 1024 +_DEFAULT_MAX_QUEUED = 32 +# Acks waiting for a 2xx. Bounded so a receiver that never answers cannot grow +# it; an id lost here only means the hint comes back, is recognised as a +# duplicate and is acked again. +_MAX_PENDING_ACKS = 1024 +# Hints waiting for the on_hint callback; a callback that falls this far +# behind loses the oldest hand-offs (the hints themselves stay queued). +_MAX_PENDING_CALLBACKS = 32 +_TRACE_ID = re.compile(r"[0-9a-f]{32}") + +ParamValue = str | int | float | bool + + +@dataclass(frozen=True) +class Hint: + """One hint, as delivered on the heartbeat response. + + ``created_at`` and ``expires_at`` are the writer's RFC3339 UTC stamps, + kept as strings: the SDK never compares them with its own clock. + ``trace_id`` is the root trace of the run the hint is about (32 lowercase + hex), or ``None`` for a hint about the instance as a whole. + """ + + id: str + code: str + template_version: int + text: str + # Read-only; left out of the hash so a hint stays hashable. + params: Mapping[str, ParamValue] = field(hash=False) + trace_id: str | None + span_ids: tuple[str, ...] + created_at: str + expires_at: str + + +def verify_hint(raw: Mapping[str, Any]) -> bool: + """Whether a received hint may be accepted. A hint that fails is dropped and acked. + + Accepts everything for now: hints are not signed yet. Signature checking + goes here once the receiver delivers signed hints. + """ + return True + + +def current_trace_id() -> str | None: + """The trace id of the current span context (32 lowercase hex), if any.""" + context = trace.get_current_span().get_span_context() + if not context.is_valid: + return 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: + return [] + try: + decoded = json.loads(body) + except (ValueError, RecursionError): + return [] + if not isinstance(decoded, dict) or decoded.get("format") not in ACCEPTED_FORMATS: + return [] + hints = decoded.get("hints") + return hints if isinstance(hints, list) else [] + + +def _is_param(value: object) -> bool: + return isinstance(value, (str, int, float, bool)) + + +def _to_hint(raw: Mapping[str, Any]) -> Hint | None: + """A :class:`Hint` from one wire hint, or ``None`` when it is malformed.""" + code, version, text = raw.get("code"), raw.get("template_version"), raw.get("text") + created_at, expires_at = raw.get("created_at"), raw.get("expires_at") + if not ( + isinstance(code, str) + and isinstance(version, int) + and not isinstance(version, bool) + and isinstance(text, str) + and isinstance(created_at, str) + and isinstance(expires_at, str) + ): + return None + params = raw.get("params", {}) + if not isinstance(params, dict) or not all( + isinstance(key, str) and _is_param(value) for key, value in params.items() + ): + return None + span_ids = raw.get("span_ids", []) + if not isinstance(span_ids, list) or not all(isinstance(s, str) for s in span_ids): + return None + trace_id = raw.get("trace_id") + if trace_id is not None: + if not isinstance(trace_id, str) or not _TRACE_ID.fullmatch(trace_id.lower()): + return None + trace_id = trace_id.lower() + return Hint( + id=raw["id"], + code=code, + template_version=version, + text=text, + params=MappingProxyType(dict(params)), + trace_id=trace_id, + span_ids=tuple(span_ids), + created_at=created_at, + expires_at=expires_at, + ) + + +class _CallbackWorker: + """Runs ``on_hint`` on its own daemon thread, never on the heartbeat thread. + + A callback that blocks or raises (``SystemExit`` included) can then never + delay or stop a liveness ping. Hand-offs wait in a bounded queue that drops + the oldest. The thread starts on the first hand-off; nothing ever joins + it, so it never holds up shutdown. + """ + + 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() + + def _fresh(self) -> None: + self._ready = threading.Condition() + self._pending: deque[Hint] = deque() + self._thread: threading.Thread | None = None + self._closed = False + + def submit(self, hint: Hint) -> None: + with self._ready: + if self._closed: + return + self._pending.append(hint) + while len(self._pending) > self._max_pending: + dropped = self._pending.popleft() + logger.debug( + "rius on_hint is behind; skipped it for the oldest hint %s", dropped.id + ) + if self._thread is None: + self._thread = threading.Thread( + target=self._run, name="rius-hint-callback", daemon=True + ) + self._thread.start() + self._ready.notify() + + def _run(self) -> None: + ready = self._ready + while True: + with ready: + while not self._pending and not self._closed: + ready.wait() + if self._closed or ready is not self._ready: + return + hint = self._pending.popleft() + 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 + if self._warned: + logger.debug("rius on_hint raised for hint %s: %r", hint.id, exc) + else: + self._warned = True + logger.warning( + "rius on_hint raised for hint %s (%r); the hint is still queued. " + "Further on_hint errors log at DEBUG", + hint.id, + exc, + ) + + def close(self) -> None: + """Stop taking hand-offs and let the thread exit. Does not wait for it.""" + with self._ready: + self._closed = True + self._pending.clear() + self._ready.notify() + + def reset(self) -> None: + """A forked child has no worker thread: start over, on fresh locks.""" + self._fresh() + + +class HintInbox: + """One client's hints: the queue, the ids it has seen, and the acks to send. + + The heartbeat thread feeds it each response body (:meth:`accept`) and asks + it for the ids to ack; the agent drains it from any thread. + """ + + def __init__( + self, + open_traces: Callable[[], Sequence[str]], + *, + per_trace: int = DEFAULT_HINTS_PER_TRACE, + max_queued: int = _DEFAULT_MAX_QUEUED, + 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, root_span) + ) + self._verify = verify + self._lock = threading.Lock() + self._queue: deque[Hint] = deque() + self._seen: OrderedDict[str, None] = OrderedDict() + self._accepted_per_trace: dict[str, int] = {} + self._pending_acks: OrderedDict[str, None] = OrderedDict() + self._skip_acks_once = False + + # -- heartbeat thread --------------------------------------------------- + + def accept(self, body: bytes | None) -> None: + """Process the hints in one response body. Never raises.""" + try: + accepted = self._accept(parse_response(body)) + except Exception as exc: # noqa: BLE001 — the hint path never breaks a ping + logger.debug("rius hints: could not process a heartbeat response: %s", exc) + return + if self._callbacks is not None: + for hint in accepted: + self._callbacks.submit(hint) + + def _accept(self, raw_hints: list[Any]) -> list[Hint]: + open_traces = {t.lower() for t in self._open_traces()} + accepted: list[Hint] = [] + with self._lock: + # The budget is per run: forget the counts of runs that have ended, + # and their undrained hints, which nobody will read and which would + # otherwise take queue slots from live ones. + for trace_id in [t for t in self._accepted_per_trace if t not in open_traces]: + del self._accepted_per_trace[trace_id] + live = deque(h for h in self._queue if h.trace_id is None or h.trace_id in open_traces) + if len(live) < len(self._queue): + pruned = len(self._queue) - len(live) + logger.debug("rius hints: pruned %d undrained hints of finished runs", pruned) + self._queue = live + for raw in raw_hints: + if not isinstance(raw, dict) or not isinstance(raw.get("id"), str): + continue # nothing to ack it by + hint_id: str = raw["id"] + self._ack(hint_id) + if hint_id in self._seen: + continue # a redelivery: acking it again is all it needs + self._remember(hint_id) + hint = self._admit(raw, open_traces) + if hint is not None: + accepted.append(hint) + return accepted + + def _admit(self, raw: dict[str, Any], open_traces: set[str]) -> Hint | None: + """Queue one new hint if every rule lets it through (lock held).""" + hint = _to_hint(raw) + if hint is None: + logger.debug("rius hints: dropped malformed hint %s", raw["id"]) + return None + if not self._verify(raw): + logger.debug("rius hints: dropped hint %s, verification failed", hint.id) + return None + if hint.trace_id is not None: + if hint.trace_id not in open_traces: + logger.debug("rius hints: dropped hint %s, its trace is not open here", hint.id) + return None + accepted = self._accepted_per_trace.get(hint.trace_id, 0) + if accepted >= self._per_trace: + logger.debug("rius hints: dropped hint %s, its run's budget is spent", hint.id) + return None + self._accepted_per_trace[hint.trace_id] = accepted + 1 + self._queue.append(hint) + while len(self._queue) > self._max_queued: + dropped = self._queue.popleft() + logger.debug("rius hints: queue full, dropped the oldest hint %s", dropped.id) + return hint + + def _remember(self, hint_id: str) -> None: + self._seen[hint_id] = None + while len(self._seen) > _SEEN_IDS: + self._seen.popitem(last=False) + + def _ack(self, hint_id: str) -> None: + self._pending_acks[hint_id] = None + while len(self._pending_acks) > _MAX_PENDING_ACKS: + self._pending_acks.popitem(last=False) + + def acks_to_send(self) -> list[str]: + """The ids for the next ping's ``acked``: at most 16, oldest first. + + Empty once after a ``413`` (:meth:`request_too_large`). + """ + with self._lock: + if self._skip_acks_once: + self._skip_acks_once = False + return [] + return list(self._pending_acks)[:MAX_ACKED_PER_PING] + + def acks_delivered(self, ids: Sequence[str]) -> None: + """A ping that carried ``ids`` got a 2xx: stop sending them.""" + with self._lock: + for hint_id in ids: + self._pending_acks.pop(hint_id, None) + + def request_too_large(self) -> None: + """A ping was refused with 413: send the next one with ``acked`` empty.""" + with self._lock: + self._skip_acks_once = True + + def reset(self) -> None: + """Forget everything; a forked child's hints 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() + if self._callbacks is not None: + self._callbacks.reset() + self._queue.clear() + self._seen.clear() + self._accepted_per_trace.clear() + self._pending_acks.clear() + self._skip_acks_once = False + + def close(self) -> None: + """Stop handing hints to ``on_hint``, without waiting for its thread.""" + if self._callbacks is not None: + self._callbacks.close() + + # -- agent side --------------------------------------------------------- + + def drain(self, trace_id: str | None) -> list[Hint]: + """Remove and return the hints for ``trace_id`` plus the instance-wide ones. + + ``None`` returns the instance-wide hints only. Oldest first. + """ + wanted = None if trace_id is None else trace_id.lower() + drained: list[Hint] = [] + kept: deque[Hint] = deque() + with self._lock: + for hint in self._queue: + (drained if hint.trace_id in (None, wanted) else kept).append(hint) + self._queue = kept + for hint in drained: + record_delivery(hint, RIUS_HINT_CHANNEL_DRAIN, self._root_span) + return drained diff --git a/tests/test_heartbeat.py b/tests/test_heartbeat.py index fb68adf..adc99c5 100644 --- a/tests/test_heartbeat.py +++ b/tests/test_heartbeat.py @@ -8,11 +8,14 @@ from __future__ import annotations +import base64 import json import logging +import os import re import threading import uuid +import warnings from http.server import BaseHTTPRequestHandler, HTTPServer from typing import Any @@ -21,7 +24,12 @@ from rius import init from rius.config import resolve_config -from rius.heartbeat import HeartbeatSender, OpenRootSpanTracker +from rius.heartbeat import ( + HeartbeatSender, + OpenRootSpanTracker, + derive_instance_id, + mint_instance_identity, +) # --------------------------------------------------------------------------- # Config surface @@ -366,6 +374,264 @@ def log_message(self, *args: Any) -> None: # silence test output thread.join(timeout=5) +def _serve_heartbeats() -> tuple[HTTPServer, threading.Thread, list[tuple[dict[str, Any], Any]]]: + received: list[tuple[dict[str, Any], Any]] = [] + + class Handler(BaseHTTPRequestHandler): + def do_POST(self) -> None: # noqa: N802 — http.server API + body = self.rfile.read(int(self.headers["Content-Length"])) + received.append((json.loads(body), self.headers)) + self.send_response(204) + self.end_headers() + + def log_message(self, *args: Any) -> None: # silence test output + pass + + server = HTTPServer(("127.0.0.1", 0), Handler) + thread = threading.Thread(target=server.serve_forever, daemon=True) + thread.start() + return server, thread, received + + +def _decode_secret(secret: str) -> bytes: + return base64.urlsafe_b64decode(secret + "=" * (-len(secret) % 4)) + + +def test_instance_id_derivation_matches_the_receiver() -> None: + # Same vector as argus-core heartbeat/secret_test.go and the TS SDK. + assert derive_instance_id(bytes(range(32))) == "630dcd29-66c4-8366-9112-5448bbb25b4f" + + +def test_minted_identity_is_a_secret_and_the_id_it_derives() -> None: + instance_id, secret = mint_instance_identity() + raw = _decode_secret(secret) + assert len(raw) == 32 and "=" not in secret + assert instance_id == derive_instance_id(raw) + assert uuid.UUID(instance_id).version == 8 + assert mint_instance_identity() != (instance_id, secret) + + +def test_init_uses_the_derived_id_for_spans_and_heartbeats( + monkeypatch: pytest.MonkeyPatch, +) -> None: + monkeypatch.delenv("RIUS_HEARTBEAT", raising=False) + client = init( + set_global=False, + service_name="svc", + api_key="k", + endpoint="http://127.0.0.1:1", + span_exporter=InMemorySpanExporter(), + ) + try: + sender = client._heartbeat # noqa: SLF001 + assert sender is not None + resource_id = client._provider.resource.attributes["service.instance.id"] # noqa: SLF001 + assert sender.instance_id == resource_id + assert sender.instance_id == derive_instance_id(_decode_secret(sender._secret or "")) # noqa: SLF001 + finally: + client.shutdown() + + +def test_a_custom_transport_pings_as_a_legacy_instance(monkeypatch: pytest.MonkeyPatch) -> None: + # It is handed the payload only, so it could never send the secret, and a + # derived id without its secret is refused on every ping. + monkeypatch.delenv("RIUS_HEARTBEAT", raising=False) + client = init( + set_global=False, + service_name="svc", + span_exporter=InMemorySpanExporter(), + heartbeat_transport=[].append, + ) + try: + sender = client._heartbeat # noqa: SLF001 + assert sender is not None + assert sender._secret is None # noqa: SLF001 + assert uuid.UUID(sender.instance_id).version == 4 + resource_id = client._provider.resource.attributes["service.instance.id"] # noqa: SLF001 + assert sender.instance_id == resource_id + finally: + client.shutdown() + + +def test_fork_reset_keeps_a_legacy_sender_legacy() -> None: + sender = HeartbeatSender( + url="http://unused", + headers={}, + interval=3600.0, + agent_name="a", + instance_id=str(uuid.uuid4()), + tracker=OpenRootSpanTracker(), + transport=lambda payload: None, + ) + before = sender.instance_id + try: + sender._reset_in_child() # noqa: SLF001 + assert sender.instance_id != before + assert sender._secret is None # noqa: SLF001 + assert uuid.UUID(sender.instance_id).version == 4 + finally: + sender.stop() + + +def test_every_ping_including_the_final_one_carries_the_secret() -> None: + server, thread, received = _serve_heartbeats() + instance_id, secret = mint_instance_identity() + try: + sender = HeartbeatSender( + url=f"http://127.0.0.1:{server.server_port}/v1/heartbeat", + headers={"Authorization": "Bearer test-key"}, + interval=3600.0, + agent_name="e2e-agent", + instance_id=instance_id, + instance_secret=secret, + tracker=OpenRootSpanTracker(), + ) + sender.start() + sender.stop() + assert [payload.get("stopped", False) for payload, _ in received] == [False, True] + assert [headers.get("Rius-Instance-Secret") for _, headers in received] == [secret, secret] + for payload, _ in received: + assert payload["instance_id"] == instance_id + assert secret not in json.dumps(payload) + finally: + server.shutdown() + thread.join(timeout=5) + + +def test_a_sender_without_a_secret_sends_no_secret_header() -> None: + server, thread, received = _serve_heartbeats() + try: + sender = HeartbeatSender( + url=f"http://127.0.0.1:{server.server_port}/v1/heartbeat", + headers={}, + interval=3600.0, + agent_name="e2e-agent", + instance_id=str(uuid.uuid4()), + tracker=OpenRootSpanTracker(), + ) + sender._send_ping() # noqa: SLF001 + assert received[0][1].get("Rius-Instance-Secret") is None + finally: + server.shutdown() + thread.join(timeout=5) + + +def test_a_caller_header_cannot_replace_the_secret() -> None: + server, thread, received = _serve_heartbeats() + instance_id, secret = mint_instance_identity() + try: + for name in ("Rius-Instance-Secret", "rius-instance-secret", "RIUS-INSTANCE-SECRET"): + sender = HeartbeatSender( + url=f"http://127.0.0.1:{server.server_port}/v1/heartbeat", + headers={"Authorization": "Bearer test-key", name: "caller-value"}, + interval=3600.0, + agent_name="e2e-agent", + instance_id=instance_id, + instance_secret=secret, + tracker=OpenRootSpanTracker(), + ) + sender._send_ping() # noqa: SLF001 + assert received[-1][1].get_all("Rius-Instance-Secret") == [secret], name + finally: + server.shutdown() + thread.join(timeout=5) + + +def test_fork_reset_mints_a_new_secret_and_its_id() -> None: + instance_id, secret = mint_instance_identity() + sender = HeartbeatSender( + url="https://ingest.example.com/v1/heartbeat", + headers={}, + interval=3600.0, + agent_name="a", + instance_id=instance_id, + instance_secret=secret, + tracker=OpenRootSpanTracker(), + transport=[].append, + ) + sender._reset_in_child() # noqa: SLF001 + try: + assert sender._secret not in (None, secret) # noqa: SLF001 + assert sender.instance_id == derive_instance_id(_decode_secret(sender._secret or "")) # noqa: SLF001 + finally: + sender.stop() + + +@pytest.mark.skipif(not hasattr(os, "fork"), reason="needs os.fork") +def test_a_real_fork_gives_the_child_its_own_derived_identity() -> None: + instance_id, secret = mint_instance_identity() + sender = HeartbeatSender( + url="https://ingest.example.com/v1/heartbeat", + headers={}, + interval=3600.0, + agent_name="a", + instance_id=instance_id, + instance_secret=secret, + tracker=OpenRootSpanTracker(), + transport=[].append, + ) + sender.start() + read_fd, write_fd = os.pipe() + with warnings.catch_warnings(): + warnings.simplefilter("ignore", DeprecationWarning) # fork with live threads + pid = os.fork() + if pid == 0: # pragma: no cover — runs in the child + os.close(read_fd) + child_secret = sender._secret or "" # noqa: SLF001 + ok = ( + sender.instance_id != instance_id + and child_secret != secret + and sender.instance_id == derive_instance_id(_decode_secret(child_secret)) + ) + os.write(write_fd, b"1" if ok else b"0") + os._exit(0) + os.close(write_fd) + try: + assert os.read(read_fd, 1) == b"1" + os.waitpid(pid, 0) + assert sender.instance_id == instance_id # the parent keeps its own + finally: + os.close(read_fd) + sender.stop() + + +def test_a_refused_secret_warns_specifically_and_never_logs_it( + caplog: pytest.LogCaptureFixture, +) -> None: + class Refuse(BaseHTTPRequestHandler): + def do_POST(self) -> None: # noqa: N802 — http.server API + self.rfile.read(int(self.headers["Content-Length"])) + self.send_response(403) + self.end_headers() + + def log_message(self, *args: Any) -> None: + pass + + server = HTTPServer(("127.0.0.1", 0), Refuse) + thread = threading.Thread(target=server.serve_forever, daemon=True) + thread.start() + instance_id, secret = mint_instance_identity() + try: + sender = HeartbeatSender( + url=f"http://127.0.0.1:{server.server_port}/v1/heartbeat", + headers={}, + interval=3600.0, + agent_name="a", + instance_id=instance_id, + instance_secret=secret, + tracker=OpenRootSpanTracker(), + ) + with caplog.at_level(logging.DEBUG, logger="rius"): + sender._send_ping() # noqa: SLF001 + sender._send_ping() # noqa: SLF001 + refused = [r for r in caplog.records if "instance secret" in r.getMessage()] + assert len(refused) == 1 and refused[0].levelno == logging.WARNING + assert all(secret not in r.getMessage() for r in caplog.records) + finally: + server.shutdown() + thread.join(timeout=5) + + # --------------------------------------------------------------------------- # atexit: a real subprocess that exits cleanly sends the stopped ping # --------------------------------------------------------------------------- diff --git a/tests/test_hints.py b/tests/test_hints.py new file mode 100644 index 0000000..5f800f2 --- /dev/null +++ b/tests/test_hints.py @@ -0,0 +1,1150 @@ +"""Hints received on the heartbeat response. + +Implements the "Hints" section of the heartbeat contract: the opt-in +``accepts`` capability, the capped response read, the SDK-side rules +(de-duplication, own-trace filter, per-trace budget, bounded queue) and the +``acked`` request field. Pings go to a real local HTTP server. +""" + +from __future__ import annotations + +import json +import logging +import os +import threading +import time +import uuid +import warnings +from collections import deque +from collections.abc import Callable, Iterator +from http.server import BaseHTTPRequestHandler, HTTPServer, ThreadingHTTPServer +from typing import Any + +import pytest +from opentelemetry.sdk.trace.export.in_memory_span_exporter import InMemorySpanExporter + +import rius +from rius import Hint, drain_hints, init +from rius.config import resolve_config +from rius.heartbeat import HeartbeatSender, OpenRootSpanTracker, mint_instance_identity +from rius.hints import HintInbox + +TRACE_A = "4bf92f3577b34da6a3ce929d0e0e4736" +TRACE_B = "0af7651916cd43dd8448eb211c80319c" + + +def _hint_id(n: int) -> str: + return f"h_{n:026d}" + + +def _wire_hint(n: int, trace_id: str | None = None, **overrides: Any) -> dict[str, Any]: + hint: dict[str, Any] = { + "id": _hint_id(n), + "code": "CF-01", + "template_version": 1, + "text": f"hint {n}", + "params": {"tool": "search_docs", "calls": 5, "broken": True}, + "span_ids": ["00f067aa0ba902b7"], + "created_at": "2026-10-28T10:00:00.000Z", + "expires_at": "2026-10-28T10:10:00.000Z", + } + if trace_id is not None: + hint["trace_id"] = trace_id + hint.update(overrides) + return hint + + +def _body(*hints: dict[str, Any], **top: Any) -> bytes: + return json.dumps({"format": "hints", "hints": list(hints), **top}).encode() + + +# --------------------------------------------------------------------------- +# A real heartbeat endpoint with scripted responses +# --------------------------------------------------------------------------- + + +class _Endpoint: + """Local heartbeat receiver: records each request, answers from a script.""" + + def __init__(self) -> None: + self.requests: list[tuple[dict[str, Any], int]] = [] + self.replies: deque[tuple[int, bytes]] = deque() + self.arrived = threading.Condition() + endpoint = self + + class Handler(BaseHTTPRequestHandler): + def do_POST(self) -> None: # noqa: N802 — http.server API + raw = self.rfile.read(int(self.headers["Content-Length"])) + # The reply is taken before the request is recorded, and the + # request recorded before answering: a test that saw a request + # arrive never races it for a reply, and a ping has returned + # only once it is recorded. + status, body = endpoint.replies.popleft() if endpoint.replies else (204, b"") + with endpoint.arrived: + endpoint.requests.append((json.loads(raw), len(raw))) + endpoint.arrived.notify_all() + self.send_response(status) + if body: + self.send_header("Content-Type", "application/json") + self.send_header("Content-Length", str(len(body))) + self.end_headers() + if body: + self.wfile.write(body) + + def log_message(self, *args: Any) -> None: # silence test output + pass + + self.server = HTTPServer(("127.0.0.1", 0), Handler) + self.thread = threading.Thread( + target=self.server.serve_forever, kwargs={"poll_interval": 0.01}, daemon=True + ) + self.thread.start() + + @property + def base_url(self) -> str: + return f"http://127.0.0.1:{self.server.server_port}" + + @property + def url(self) -> str: + return self.base_url + "/v1/heartbeat" + + def reply(self, status: int, body: bytes = b"") -> None: + self.replies.append((status, body)) + + def payloads(self) -> list[dict[str, Any]]: + return [payload for payload, _ in self.requests] + + def wait_for(self, count: int, timeout: float = 5.0) -> None: + with self.arrived: + assert self.arrived.wait_for(lambda: len(self.requests) >= count, timeout) + + def close(self) -> None: + self.server.shutdown() + self.thread.join(timeout=5) + + +@pytest.fixture +def endpoint() -> Iterator[_Endpoint]: + served = _Endpoint() + yield served + served.close() + + +def _sender( + endpoint: _Endpoint, + *, + inbox: HintInbox | None = None, + tracker: OpenRootSpanTracker | None = None, + agent_name: str = "agent", + interval: float = 3600.0, + url: str | None = None, +) -> HeartbeatSender: + instance_id, secret = mint_instance_identity() + return HeartbeatSender( + url=url or endpoint.url, + headers={"Authorization": "Bearer k"}, + interval=interval, + agent_name=agent_name, + instance_id=instance_id, + instance_secret=secret, + tracker=tracker or OpenRootSpanTracker(), + hints=inbox, + ) + + +def _open(*trace_ids: str) -> OpenRootSpanTracker: + tracker = OpenRootSpanTracker() + for trace_id in trace_ids: + tracker._on_root_start(trace_id) # noqa: SLF001 — test wiring + return tracker + + +def _inbox(tracker: OpenRootSpanTracker, **kwargs: Any) -> HintInbox: + return HintInbox(open_traces=tracker.open_trace_ids, **kwargs) + + +def _ids(hints: list[Hint]) -> list[str]: + return [hint.id for hint in hints] + + +def _eventually(condition: Callable[[], bool], timeout: float = 5.0) -> bool: + deadline = time.monotonic() + timeout + while time.monotonic() < deadline: + if condition(): + return True + time.sleep(0.01) + return condition() + + +# --------------------------------------------------------------------------- +# Config surface +# --------------------------------------------------------------------------- + + +def test_hints_are_off_by_default(monkeypatch: pytest.MonkeyPatch) -> None: + monkeypatch.delenv("RIUS_HINTS", raising=False) + assert resolve_config().hints is False + + +def test_hints_on_via_env(monkeypatch: pytest.MonkeyPatch) -> None: + monkeypatch.setenv("RIUS_HINTS", "true") + assert resolve_config().hints is True + + +def test_hints_argument_wins_over_env(monkeypatch: pytest.MonkeyPatch) -> None: + monkeypatch.setenv("RIUS_HINTS", "true") + assert resolve_config(hints=False).hints is False + + +def test_hints_per_trace_defaults_to_three(monkeypatch: pytest.MonkeyPatch) -> None: + monkeypatch.delenv("RIUS_HINTS_PER_TRACE", raising=False) + assert resolve_config().hints_per_trace == 3 + + +def test_hints_per_trace_from_env_and_argument(monkeypatch: pytest.MonkeyPatch) -> None: + monkeypatch.setenv("RIUS_HINTS_PER_TRACE", "5") + assert resolve_config().hints_per_trace == 5 + assert resolve_config(hints_per_trace=1).hints_per_trace == 1 + + +def test_hints_per_trace_rejects_junk_and_negatives( + monkeypatch: pytest.MonkeyPatch, caplog: pytest.LogCaptureFixture +) -> None: + monkeypatch.setenv("RIUS_HINTS_PER_TRACE", "many") + with caplog.at_level(logging.WARNING): + assert resolve_config().hints_per_trace == 3 + assert resolve_config(hints_per_trace=-2).hints_per_trace == 0 + assert any("RIUS_HINTS_PER_TRACE" in r.getMessage() for r in caplog.records) + assert any("hints_per_trace" in r.getMessage() for r in caplog.records) + + +# --------------------------------------------------------------------------- +# Capability: accepts / acked only when hints are on +# --------------------------------------------------------------------------- + + +def test_hints_off_sends_no_accepts_and_ignores_a_body(endpoint: _Endpoint) -> None: + endpoint.reply(200, _body(_wire_hint(1))) + sender = _sender(endpoint) + sender._send_ping() # noqa: SLF001 + payload = endpoint.payloads()[0] + assert "accepts" not in payload + assert "acked" not in payload + + +def test_hints_on_sends_accepts_and_an_empty_acked(endpoint: _Endpoint) -> None: + sender = _sender(endpoint, inbox=_inbox(_open())) + sender._send_ping() # noqa: SLF001 + payload = endpoint.payloads()[0] + assert payload["accepts"] == ["hints"] + assert payload["acked"] == [] + + +def test_a_sender_without_a_secret_never_asks_for_hints(endpoint: _Endpoint) -> None: + # The receiver delivers only to authenticated pings, so a legacy sender + # asking for hints would only ever get nothing back. + sender = HeartbeatSender( + url=endpoint.url, + headers={}, + interval=3600.0, + agent_name="a", + instance_id=str(uuid.uuid4()), + tracker=OpenRootSpanTracker(), + hints=_inbox(_open()), + ) + sender._send_ping() # noqa: SLF001 + assert "accepts" not in endpoint.payloads()[0] + + +# --------------------------------------------------------------------------- +# Response parsing +# --------------------------------------------------------------------------- + + +def test_a_hint_is_parsed_into_a_frozen_hint(endpoint: _Endpoint) -> None: + inbox = _inbox(_open(TRACE_A)) + endpoint.reply(200, _body(_wire_hint(1, TRACE_A))) + _sender(endpoint, inbox=inbox)._send_ping() # noqa: SLF001 + [hint] = inbox.drain(TRACE_A) + assert hint == Hint( + id=_hint_id(1), + code="CF-01", + template_version=1, + text="hint 1", + params={"tool": "search_docs", "calls": 5, "broken": True}, + trace_id=TRACE_A, + span_ids=("00f067aa0ba902b7",), + created_at="2026-10-28T10:00:00.000Z", + expires_at="2026-10-28T10:10:00.000Z", + ) + with pytest.raises(AttributeError): + hint.text = "changed" # type: ignore[misc] + + +def test_unknown_fields_are_ignored(endpoint: _Endpoint) -> None: + inbox = _inbox(_open()) + endpoint.reply(200, _body(_wire_hint(1, signature="sig", later={"x": 1}), extra=True)) + _sender(endpoint, inbox=inbox)._send_ping() # noqa: SLF001 + assert _ids(inbox.drain(None)) == [_hint_id(1)] + + +def test_an_instance_wide_hint_has_no_trace_id(endpoint: _Endpoint) -> None: + inbox = _inbox(_open()) + endpoint.reply(200, _body(_wire_hint(1))) + _sender(endpoint, inbox=inbox)._send_ping() # noqa: SLF001 + [hint] = inbox.drain(None) + assert hint.trace_id is None + + +@pytest.mark.parametrize( + "body", + [ + b"", + b"not json", + b"\xff\xfe", + b"[]", + b'{"hints": []}', + json.dumps({"format": "hints.v2", "hints": [_wire_hint(1)]}).encode(), + json.dumps({"format": "hints", "hints": {"id": "h_1"}}).encode(), + json.dumps({"format": "hints"}).encode(), + ], + ids=["empty", "not-json", "not-utf8", "list", "no-format", "unasked-format", "dict", "none"], +) +def test_a_body_of_the_wrong_kind_means_no_hints( + endpoint: _Endpoint, body: bytes, caplog: pytest.LogCaptureFixture +) -> None: + inbox = _inbox(_open()) + endpoint.reply(200, body) + endpoint.reply(204) + sender = _sender(endpoint, inbox=inbox) + with caplog.at_level(logging.WARNING, logger="rius"): + sender._send_ping() # noqa: SLF001 + sender._send_ping() # noqa: SLF001 + assert inbox.drain(None) == [] + assert endpoint.payloads()[1]["acked"] == [] + assert not caplog.records # a liveness ping that got a 2xx is not a delivery failure + + +def test_a_malformed_hint_is_dropped_and_acked_but_its_neighbours_are_kept( + endpoint: _Endpoint, +) -> None: + inbox = _inbox(_open()) + endpoint.reply( + 200, + _body( + _wire_hint(1, template_version="one"), + _wire_hint(2, trace_id="NOT-A-TRACE"), + {"no": "id"}, + "a string", + _wire_hint(3), + ), + ) + sender = _sender(endpoint, inbox=inbox) + sender._send_ping() # noqa: SLF001 + sender._send_ping() # noqa: SLF001 + assert _ids(inbox.drain(None)) == [_hint_id(3)] + assert endpoint.payloads()[1]["acked"] == [_hint_id(1), _hint_id(2), _hint_id(3)] + + +def test_a_body_over_64_kib_means_no_hints(endpoint: _Endpoint) -> None: + inbox = _inbox(_open()) + body = _body(_wire_hint(1), pad="x" * (64 * 1024)) + assert len(body) > 64 * 1024 + endpoint.reply(200, body) + _sender(endpoint, inbox=inbox)._send_ping() # noqa: SLF001 + assert inbox.drain(None) == [] + + +def test_a_body_of_exactly_64_kib_is_read(endpoint: _Endpoint) -> None: + inbox = _inbox(_open()) + body = _body(_wire_hint(1)) + body = body[:-1] + b" " * (64 * 1024 - len(body)) + b"}" + assert len(body) == 64 * 1024 + endpoint.reply(200, body) + _sender(endpoint, inbox=inbox)._send_ping() # noqa: SLF001 + assert _ids(inbox.drain(None)) == [_hint_id(1)] + + +def test_a_stopped_pings_body_is_ignored(endpoint: _Endpoint) -> None: + inbox = _inbox(_open()) + endpoint.reply(200, _body(_wire_hint(1))) + _sender(endpoint, inbox=inbox)._send_ping(stopped=True) # noqa: SLF001 + assert inbox.drain(None) == [] + + +class _SlowBody(BaseHTTPRequestHandler): + """Answers 200 with a large body whose bulk arrives only after a pause.""" + + pause = 1.5 + + def do_POST(self) -> None: # noqa: N802 — http.server API + self.rfile.read(int(self.headers["Content-Length"])) + self.send_response(200) + self.send_header("Content-Length", str(1_000_000)) + self.end_headers() + try: + self.wfile.write(b"{" + b" " * 15) + self.wfile.flush() + time.sleep(self.pause) + self.wfile.write(b" " * (1_000_000 - 16)) + except OSError: + pass # the client closed without reading, as it should + + def log_message(self, *args: Any) -> None: # silence test output + pass + + +@pytest.fixture +def slow_body_url() -> Iterator[str]: + server = ThreadingHTTPServer(("127.0.0.1", 0), _SlowBody) + server.daemon_threads = True + thread = threading.Thread( + target=server.serve_forever, kwargs={"poll_interval": 0.01}, daemon=True + ) + thread.start() + yield f"http://127.0.0.1:{server.server_port}/v1/heartbeat" + server.shutdown() + thread.join(timeout=5) + + +def _timed(call: Callable[[], None]) -> float: + started = time.monotonic() + call() + return time.monotonic() - started + + +def test_the_body_is_read_only_by_a_hints_ping(endpoint: _Endpoint, slow_body_url: str) -> None: + hints_off = _sender(endpoint, url=slow_body_url) + hints_on = _sender(endpoint, url=slow_body_url, inbox=_inbox(_open())) + # Hints off and the stopped ping close the response without reading it, + # exactly as before hints existed. + assert _timed(hints_off._send_ping) < 1.0 # noqa: SLF001 + assert _timed(lambda: hints_off._send_ping(stopped=True)) < 1.0 # noqa: SLF001 + assert _timed(lambda: hints_on._send_ping(stopped=True)) < 1.0 # noqa: SLF001 + # The control: a hints ping does read, so it waits for the slow body. + assert _timed(hints_on._send_ping) >= 1.0 # noqa: SLF001 + + +# --------------------------------------------------------------------------- +# Rules: de-duplication, own traces, budget, queue +# --------------------------------------------------------------------------- + + +def test_a_redelivered_hint_is_queued_once_and_acked_again(endpoint: _Endpoint) -> None: + inbox = _inbox(_open()) + sender = _sender(endpoint, inbox=inbox) + endpoint.reply(200, _body(_wire_hint(1))) + endpoint.reply(200, _body(_wire_hint(1))) + sender._send_ping() # noqa: SLF001 + sender._send_ping() # noqa: SLF001 — carries the first ack, gets the hint again + sender._send_ping() # noqa: SLF001 + assert _ids(inbox.drain(None)) == [_hint_id(1)] + assert [p["acked"] for p in endpoint.payloads()] == [[], [_hint_id(1)], [_hint_id(1)]] + + +def test_dedupe_remembers_the_last_1024_ids() -> None: + inbox = _inbox(_open(), max_queued=2000) + for start in range(0, 1025, 100): # one body holds ~250 under the 64 KiB cap + inbox.accept(_body(*(_wire_hint(n) for n in range(start, min(start + 100, 1025))))) + assert len(inbox.drain(None)) == 1025 + # Of 1,025 ids, the oldest (0) has been forgotten and the next (1) is kept. + inbox.accept(_body(_wire_hint(1))) + assert inbox.drain(None) == [] + inbox.accept(_body(_wire_hint(0))) + assert _ids(inbox.drain(None)) == [_hint_id(0)] + + +def test_a_hint_for_a_trace_that_is_not_open_here_is_dropped_and_acked( + endpoint: _Endpoint, +) -> None: + inbox = _inbox(_open(TRACE_A)) + sender = _sender(endpoint, inbox=inbox) + endpoint.reply(200, _body(_wire_hint(1, TRACE_B), _wire_hint(2, TRACE_A))) + sender._send_ping() # noqa: SLF001 + sender._send_ping() # noqa: SLF001 + assert _ids(inbox.drain(TRACE_B)) == [] + assert _ids(inbox.drain(TRACE_A)) == [_hint_id(2)] + assert endpoint.payloads()[1]["acked"] == [_hint_id(1), _hint_id(2)] + + +def test_trace_ids_are_compared_as_lowercase_hex(endpoint: _Endpoint) -> None: + inbox = _inbox(_open(TRACE_A)) + endpoint.reply(200, _body(_wire_hint(1, TRACE_A.upper()))) + _sender(endpoint, inbox=inbox)._send_ping() # noqa: SLF001 + [hint] = inbox.drain(TRACE_A.upper()) + assert hint.trace_id == TRACE_A + + +def test_expires_at_is_never_compared_with_the_local_clock(endpoint: _Endpoint) -> None: + inbox = _inbox(_open()) + long_gone = _wire_hint( + 1, created_at="2001-01-01T00:00:00.000Z", expires_at="2001-01-01T00:10:00.000Z" + ) + endpoint.reply(200, _body(long_gone)) + _sender(endpoint, inbox=inbox)._send_ping() # noqa: SLF001 + assert _ids(inbox.drain(None)) == [_hint_id(1)] + + +def test_at_most_three_hints_per_trace_by_default(endpoint: _Endpoint) -> None: + inbox = _inbox(_open(TRACE_A, TRACE_B)) + sender = _sender(endpoint, inbox=inbox) + endpoint.reply(200, _body(*(_wire_hint(n, TRACE_A) for n in range(1, 5)))) + endpoint.reply(200, _body(_wire_hint(5, TRACE_A), _wire_hint(6, TRACE_B), _wire_hint(7))) + sender._send_ping() # noqa: SLF001 + sender._send_ping() # noqa: SLF001 + sender._send_ping() # noqa: SLF001 + # The budget counts accepted hints, not queued ones: draining frees nothing. + assert _ids(inbox.drain(TRACE_A)) == [_hint_id(n) for n in (1, 2, 3, 7)] + assert _ids(inbox.drain(TRACE_B)) == [_hint_id(6)] + acked = [i for p in endpoint.payloads() for i in p["acked"]] + assert sorted(acked) == [_hint_id(n) for n in range(1, 8)] + + +def test_the_per_trace_budget_is_configurable() -> None: + inbox = _inbox(_open(TRACE_A), per_trace=1) + inbox.accept(_body(_wire_hint(1, TRACE_A), _wire_hint(2, TRACE_A))) + assert _ids(inbox.drain(TRACE_A)) == [_hint_id(1)] + + +def test_a_full_queue_drops_the_oldest_with_a_debug_log( + caplog: pytest.LogCaptureFixture, +) -> None: + inbox = _inbox(_open(), max_queued=2) + with caplog.at_level(logging.DEBUG, logger="rius.hints"): + inbox.accept(_body(_wire_hint(1), _wire_hint(2), _wire_hint(3))) + assert _ids(inbox.drain(None)) == [_hint_id(2), _hint_id(3)] + assert any(_hint_id(1) in r.getMessage() for r in caplog.records) + assert inbox.acks_to_send() == [_hint_id(1), _hint_id(2), _hint_id(3)] + + +def test_queued_hints_of_a_finished_run_are_pruned_before_they_take_a_slot() -> None: + open_now = [TRACE_A] + inbox = HintInbox(open_traces=lambda: open_now, max_queued=2) + inbox.accept(_body(_wire_hint(1))) + inbox.accept(_body(_wire_hint(2, TRACE_A))) + open_now.clear() # run A ends before anyone drained its hint + inbox.accept(_body(_wire_hint(3))) + assert _ids(inbox.drain(None)) == [_hint_id(1), _hint_id(3)] + assert inbox.drain(TRACE_A) == [] + + +def test_a_hint_that_fails_verification_is_dropped_and_acked() -> None: + inbox = _inbox(_open(), verify=lambda raw: raw["id"] != _hint_id(1)) + inbox.accept(_body(_wire_hint(1), _wire_hint(2))) + assert _ids(inbox.drain(None)) == [_hint_id(2)] + assert inbox.acks_to_send() == [_hint_id(1), _hint_id(2)] + + +# --------------------------------------------------------------------------- +# on_hint callback +# --------------------------------------------------------------------------- + + +def test_on_hint_is_called_once_per_newly_accepted_hint(endpoint: _Endpoint) -> None: + seen: list[tuple[str, str]] = [] + inbox = _inbox( + _open(), on_hint=lambda hint: seen.append((hint.id, threading.current_thread().name)) + ) + sender = _sender(endpoint, inbox=inbox) + endpoint.reply(200, _body(_wire_hint(1), _wire_hint(2, TRACE_B))) + endpoint.reply(200, _body(_wire_hint(1))) + sender.start() + endpoint.wait_for(1) + sender._send_ping() # noqa: SLF001 + assert _eventually(lambda: len(seen) == 1) + sender.stop() + assert seen == [(_hint_id(1), "rius-hint-callback")] + + +def test_an_on_hint_exception_is_logged_and_never_breaks_the_ping( + endpoint: _Endpoint, caplog: pytest.LogCaptureFixture +) -> None: + def explode(hint: Hint) -> None: + raise RuntimeError("callback bug") + + inbox = _inbox(_open(), on_hint=explode) + sender = _sender(endpoint, inbox=inbox) + endpoint.reply(200, _body(_wire_hint(1), _wire_hint(2))) + with caplog.at_level(logging.DEBUG, logger="rius"): + sender._send_ping() # noqa: SLF001 + sender._send_ping() # noqa: SLF001 + assert _eventually(lambda: sum("on_hint" in r.getMessage() for r in caplog.records) == 2) + assert _ids(inbox.drain(None)) == [_hint_id(1), _hint_id(2)] + assert endpoint.payloads()[1]["acked"] == [_hint_id(1), _hint_id(2)] + assert not any("heartbeat delivery failed" in r.getMessage() for r in caplog.records) + + +def test_a_blocking_on_hint_never_delays_a_ping_or_stop(endpoint: _Endpoint) -> None: + entered, release = threading.Event(), threading.Event() + + def block(hint: Hint) -> None: + entered.set() + release.wait(10) + + sender = _sender(endpoint, inbox=_inbox(_open(), on_hint=block), interval=0.05) + endpoint.reply(200, _body(_wire_hint(1), _wire_hint(2))) + sender.start() + try: + assert entered.wait(5) + pinged = len(endpoint.requests) + endpoint.wait_for(pinged + 3, timeout=2) # pings go on while it blocks + assert _timed(sender.stop) < 1.0 + finally: + release.set() + + +def test_an_on_hint_raising_system_exit_leaves_pings_and_callbacks_running( + endpoint: _Endpoint, +) -> None: + calls: list[str] = [] + + def exit_on_first(hint: Hint) -> None: + calls.append(hint.id) + if hint.id == _hint_id(1): + raise SystemExit(1) + + sender = _sender(endpoint, inbox=_inbox(_open(), on_hint=exit_on_first), interval=0.05) + endpoint.reply(200, _body(_wire_hint(1))) + endpoint.reply(200, _body(_wire_hint(2))) + sender.start() + try: + endpoint.wait_for(5) + assert _eventually(lambda: calls == [_hint_id(1), _hint_id(2)]) + finally: + sender.stop() + + +def test_a_full_callback_queue_drops_the_oldest_hand_off( + caplog: pytest.LogCaptureFixture, +) -> None: + entered, release = threading.Event(), threading.Event() + calls: list[str] = [] + + def block_on_first(hint: Hint) -> None: + calls.append(hint.id) + if hint.id == _hint_id(1): + entered.set() + release.wait(10) + + inbox = _inbox(_open(), on_hint=block_on_first, max_pending_callbacks=2) + with caplog.at_level(logging.DEBUG, logger="rius.hints"): + inbox.accept(_body(_wire_hint(1))) + assert entered.wait(5) + inbox.accept(_body(_wire_hint(2), _wire_hint(3), _wire_hint(4))) + release.set() + assert _eventually(lambda: len(calls) == 3) + assert calls == [_hint_id(1), _hint_id(3), _hint_id(4)] + assert any(_hint_id(2) in r.getMessage() for r in caplog.records) + # The queue for drain_hints is separate and keeps every hint. + assert len(inbox.drain(None)) == 4 + + +# --------------------------------------------------------------------------- +# Acks +# --------------------------------------------------------------------------- + + +def test_an_ack_is_carried_until_a_ping_that_carried_it_gets_a_2xx(endpoint: _Endpoint) -> None: + inbox = _inbox(_open()) + sender = _sender(endpoint, inbox=inbox) + endpoint.reply(200, _body(_wire_hint(1))) + endpoint.reply(503) + endpoint.reply(500) + endpoint.reply(204) + for _ in range(5): + sender._send_ping() # noqa: SLF001 + assert [p["acked"] for p in endpoint.payloads()] == [ + [], + [_hint_id(1)], + [_hint_id(1)], + [_hint_id(1)], + [], + ] + + +def test_acked_holds_at_most_16_ids_oldest_first(endpoint: _Endpoint) -> None: + inbox = _inbox(_open(), max_queued=64) + sender = _sender(endpoint, inbox=inbox) + endpoint.reply(200, _body(*(_wire_hint(n) for n in range(20)))) + for _ in range(3): + sender._send_ping() # noqa: SLF001 + acked = [p["acked"] for p in endpoint.payloads()] + assert acked[1] == [_hint_id(n) for n in range(16)] + assert acked[2] == [_hint_id(n) for n in range(16, 20)] + + +def test_acks_are_trimmed_to_keep_the_request_within_3_5_kib(endpoint: _Endpoint) -> None: + inbox = _inbox(_open(), max_queued=64) + # A long agent name leaves room for only a few ids under 3,584 bytes. + sender = _sender(endpoint, inbox=inbox, agent_name="a" * 3100) + endpoint.reply(200, _body(*(_wire_hint(n) for n in range(16)))) + for _ in range(6): + sender._send_ping() # noqa: SLF001 + sizes = [size for _, size in endpoint.requests] + acked = [p["acked"] for p in endpoint.payloads()] + assert all(size <= 3584 for size in sizes) + assert 0 < len(acked[1]) < 16 + assert acked[1] == [_hint_id(n) for n in range(len(acked[1]))] + sent = [i for ids in acked for i in ids] + assert sent == [_hint_id(n) for n in range(16)] # every id goes, in order, exactly once + + +def test_an_oversized_payload_is_still_sent_with_no_acks(endpoint: _Endpoint) -> None: + inbox = _inbox(_open()) + sender = _sender(endpoint, inbox=inbox, agent_name="a" * 5000) + endpoint.reply(200, _body(_wire_hint(1))) + sender._send_ping() # noqa: SLF001 + sender._send_ping() # noqa: SLF001 + assert [p["acked"] for p in endpoint.payloads()] == [[], []] + assert inbox.acks_to_send() == [_hint_id(1)] + + +def test_after_a_413_the_next_ping_sends_acked_empty(endpoint: _Endpoint) -> None: + inbox = _inbox(_open()) + sender = _sender(endpoint, inbox=inbox) + endpoint.reply(200, _body(_wire_hint(1))) + endpoint.reply(413) + for _ in range(4): + sender._send_ping() # noqa: SLF001 + assert [p["acked"] for p in endpoint.payloads()] == [[], [_hint_id(1)], [], [_hint_id(1)]] + + +# --------------------------------------------------------------------------- +# Fork +# --------------------------------------------------------------------------- + + +def test_a_forked_child_forgets_the_parents_hints_acks_and_ids(endpoint: _Endpoint) -> None: + inbox = _inbox(_open()) + sender = _sender(endpoint, inbox=inbox) + endpoint.reply(200, _body(_wire_hint(1), _wire_hint(2))) + sender._send_ping() # noqa: SLF001 + sender._reset_in_child() # noqa: SLF001 — what the fork hook runs in the child + try: + assert inbox.drain(None) == [] + assert inbox.acks_to_send() == [] + inbox.accept(_body(_wire_hint(1))) # the parent's id is new to the child + assert _ids(inbox.drain(None)) == [_hint_id(1)] + finally: + sender.stop() + + +@pytest.mark.skipif(not hasattr(os, "fork"), reason="needs os.fork") +def test_a_real_fork_resets_the_inbox_and_its_callback_worker(endpoint: _Endpoint) -> None: + calls: list[str] = [] + inbox = _inbox(_open(), on_hint=lambda hint: calls.append(hint.id)) + sender = _sender(endpoint, inbox=inbox) + endpoint.reply(200, _body(_wire_hint(1))) + sender.start() + try: + assert _eventually(lambda: calls == [_hint_id(1)]) + assert inbox.acks_to_send() == [_hint_id(1)] + read_fd, write_fd = os.pipe() + with warnings.catch_warnings(): + warnings.simplefilter("ignore", DeprecationWarning) # fork with live threads + pid = os.fork() + if pid == 0: # pragma: no cover — runs in the child + os.close(read_fd) + ok = inbox.drain(None) == [] and inbox.acks_to_send() == [] + inbox.accept(_body(_wire_hint(1))) # new to the child + ok = ok and _ids(inbox.drain(None)) == [_hint_id(1)] + ok = ok and _eventually(lambda: calls == [_hint_id(1), _hint_id(1)]) + os.write(write_fd, b"1" if ok else b"0") + os._exit(0) + os.close(write_fd) + try: + assert os.read(read_fd, 1) == b"1" + os.waitpid(pid, 0) + assert _ids(inbox.drain(None)) == [_hint_id(1)] # the parent keeps its own + finally: + os.close(read_fd) + finally: + sender.stop() + + +def test_drain_and_accept_running_together_lose_and_duplicate_nothing() -> None: + inbox = _inbox(_open(), max_queued=10_000) + total = 3000 + fed = threading.Event() + drained: list[list[Hint]] = [[], []] + + def feed() -> None: + for start in range(0, total, 50): + inbox.accept(_body(*(_wire_hint(n) for n in range(start, start + 50)))) + fed.set() + + def drain(into: list[Hint]) -> None: + while not fed.is_set(): + into.extend(inbox.drain(None)) + into.extend(inbox.drain(None)) + + threads = [threading.Thread(target=feed)] + [ + threading.Thread(target=drain, args=(into,)) for into in drained + ] + for thread in threads: + thread.start() + for thread in threads: + thread.join(timeout=30) + got = sorted(_ids(drained[0] + drained[1])) + assert got == [_hint_id(n) for n in range(total)] + + +# --------------------------------------------------------------------------- +# init() wiring and the public drain +# --------------------------------------------------------------------------- + + +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, + **kwargs, + ) + + +def test_a_custom_transport_keeps_hints_off_and_says_why( + caplog: pytest.LogCaptureFixture, +) -> None: + sent: list[dict[str, Any]] = [] + with caplog.at_level(logging.WARNING, logger="rius"): + client = init( + set_global=False, + service_name="svc", + heartbeat=True, + hints=True, + heartbeat_transport=sent.append, + span_exporter=InMemorySpanExporter(), + ) + try: + assert client.drain_hints() == [] + finally: + client.shutdown() + assert sent and all("accepts" not in payload for payload in sent) + messages = [r.getMessage() for r in caplog.records if "hints" in r.getMessage()] + assert len(messages) == 1 + assert "heartbeat_transport" in messages[0] + + +@pytest.mark.parametrize( + ("options", "reason"), + [ + ({"heartbeat": False, "api_key": "k"}, "heartbeat is off"), + ({"heartbeat": True, "disabled": True, "api_key": "k"}, "disabled"), + ({"heartbeat": True}, "credentials"), + ], + ids=["heartbeat-off", "kill-switch", "no-credentials"], +) +def test_hints_asked_for_but_off_warn_once_with_the_reason( + options: dict[str, Any], + reason: str, + monkeypatch: pytest.MonkeyPatch, + caplog: pytest.LogCaptureFixture, +) -> None: + monkeypatch.delenv("RIUS_API_KEY", raising=False) + with caplog.at_level(logging.WARNING, logger="rius"): + client = init( + set_global=False, + service_name="svc", + endpoint="http://127.0.0.1:1", + hints=True, + span_exporter=InMemorySpanExporter(), + **options, + ) + client.shutdown() + messages = [r.getMessage() for r in caplog.records if "hints" in r.getMessage()] + assert len(messages) == 1, messages + assert reason in messages[0] + assert caplog.records[0].levelno == logging.WARNING + + +def test_hints_that_are_on_warn_nothing( + endpoint: _Endpoint, caplog: pytest.LogCaptureFixture +) -> None: + with caplog.at_level(logging.WARNING, logger="rius"): + client = _hint_client(endpoint, set_global=False, hints=True) + client.shutdown() + assert not [r for r in caplog.records if "hints" in r.getMessage()] + + +def test_hints_off_by_default_in_init(endpoint: _Endpoint, monkeypatch: pytest.MonkeyPatch) -> None: + monkeypatch.delenv("RIUS_HINTS", raising=False) + client = _hint_client(endpoint, set_global=False) + try: + endpoint.wait_for(1) + assert "accepts" not in endpoint.payloads()[0] + assert client.drain_hints() == [] + finally: + client.shutdown() + + +def test_init_on_hint_and_drain_by_the_current_trace(endpoint: _Endpoint) -> None: + received: list[Hint] = [] + client = _hint_client(endpoint, set_global=False, hints=True, on_hint=received.append) + try: + endpoint.wait_for(1) + assert endpoint.payloads()[0]["accepts"] == ["hints"] + tracer = client.get_tracer() + other = tracer.start_span("other run") + other_trace = format(other.get_span_context().trace_id, "032x") + 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), _wire_hint(2, other_trace), _wire_hint(3)), + ) + assert client._heartbeat is not None # noqa: SLF001 + client._heartbeat._send_ping() # noqa: SLF001 + assert _eventually(lambda: len(received) == 3) + assert _ids(received) == [_hint_id(1), _hint_id(2), _hint_id(3)] + with tracer.start_as_current_span("model call"): + assert _ids(client.drain_hints()) == [_hint_id(1), _hint_id(3)] + assert client.drain_hints() == [] + assert client.drain_hints() == [] # no current trace: instance-wide only + assert _ids(client.drain_hints(trace_id=other_trace)) == [_hint_id(2)] + other.end() + finally: + client.shutdown() + + +def test_the_module_drain_uses_the_global_client(endpoint: _Endpoint) -> None: + assert drain_hints() == [] # no client yet + client = _hint_client(endpoint, hints=True, instruments=[]) + try: + endpoint.wait_for(1) + endpoint.reply(200, _body(_wire_hint(1))) + assert client._heartbeat is not None # noqa: SLF001 + client._heartbeat._send_ping() # noqa: SLF001 + assert _ids(drain_hints()) == [_hint_id(1)] + finally: + client.shutdown() + assert drain_hints() == [] + + +def test_init_passes_the_per_trace_budget_through(endpoint: _Endpoint) -> None: + client = _hint_client(endpoint, set_global=False, hints=True, hints_per_trace=1) + 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), _wire_hint(2, this_trace))) + assert client._heartbeat is not None # noqa: SLF001 + client._heartbeat._send_ping() # noqa: SLF001 + assert _ids(client.drain_hints()) == [_hint_id(1)] + finally: + client.shutdown() + + +def test_a_second_client_keeps_its_own_hints(endpoint: _Endpoint) -> None: + first = _hint_client(endpoint, set_global=False, hints=True) + second = _hint_client(endpoint, set_global=False, hints=True) + try: + endpoint.wait_for(2) + endpoint.reply(200, _body(_wire_hint(1))) + assert first._heartbeat is not None # noqa: SLF001 + first._heartbeat._send_ping() # noqa: SLF001 + assert second.drain_hints() == [] + assert _ids(first.drain_hints()) == [_hint_id(1)] + finally: + first.shutdown() + second.shutdown() + + +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()