|
| 1 | +"""Assertions that emitted spans use OTel semantic-convention attribute names. |
| 2 | +
|
| 3 | +Test-side enforcement of the rule "use the official OTel semconv attribute |
| 4 | +names where one exists" (see `src/observability/spans.py` and |
| 5 | +`docs/INVARIANTS.md`). |
| 6 | +
|
| 7 | +The scaffold ships only semconv-defined keys (no custom ones); the |
| 8 | +`ALLOWED_CUSTOM_KEYS` set below is intentionally empty. When a project |
| 9 | +that extends this template needs a custom attribute (e.g. |
| 10 | +`agent.tool_calls_count`), it MUST add a constant to |
| 11 | +`src/observability/spans.py` AND register it in `ALLOWED_CUSTOM_KEYS` — |
| 12 | +the registry-closure test fails otherwise. That's the forcing function |
| 13 | +that keeps custom keys to their documented set rather than letting them |
| 14 | +proliferate as one-off raw strings. |
| 15 | +""" |
| 16 | + |
| 17 | +from __future__ import annotations |
| 18 | + |
| 19 | +from typing import TYPE_CHECKING |
| 20 | + |
| 21 | +import pytest |
| 22 | +from opentelemetry import trace |
| 23 | +from opentelemetry.sdk.trace import TracerProvider |
| 24 | +from opentelemetry.sdk.trace.export import SimpleSpanProcessor |
| 25 | +from opentelemetry.sdk.trace.export.in_memory_span_exporter import ( |
| 26 | + InMemorySpanExporter, |
| 27 | +) |
| 28 | + |
| 29 | +from src.observability import spans as spans_module |
| 30 | +from src.observability.spans import ( |
| 31 | + DB_QUERY_TEXT, |
| 32 | + DB_RESPONSE_RETURNED_ROWS, |
| 33 | + GENAI_CONVERSATION_ID, |
| 34 | + GENAI_OPERATION_NAME, |
| 35 | + GENAI_PROVIDER_NAME, |
| 36 | + GENAI_REQUEST_MODEL, |
| 37 | + GENAI_TOOL_CALL_ARGUMENTS, |
| 38 | + GENAI_TOOL_CALL_RESULT, |
| 39 | + GENAI_TOOL_NAME, |
| 40 | + GENAI_USAGE_INPUT_TOKENS, |
| 41 | + GENAI_USAGE_OUTPUT_TOKENS, |
| 42 | + agent_span, |
| 43 | +) |
| 44 | + |
| 45 | +if TYPE_CHECKING: |
| 46 | + from collections.abc import Sequence |
| 47 | + |
| 48 | + from opentelemetry.sdk.trace import ReadableSpan |
| 49 | + |
| 50 | + |
| 51 | +SEMCONV_KEYS: frozenset[str] = frozenset( |
| 52 | + { |
| 53 | + GENAI_CONVERSATION_ID, |
| 54 | + GENAI_REQUEST_MODEL, |
| 55 | + GENAI_OPERATION_NAME, |
| 56 | + GENAI_PROVIDER_NAME, |
| 57 | + GENAI_USAGE_INPUT_TOKENS, |
| 58 | + GENAI_USAGE_OUTPUT_TOKENS, |
| 59 | + GENAI_TOOL_NAME, |
| 60 | + GENAI_TOOL_CALL_ARGUMENTS, |
| 61 | + GENAI_TOOL_CALL_RESULT, |
| 62 | + DB_QUERY_TEXT, |
| 63 | + DB_RESPONSE_RETURNED_ROWS, |
| 64 | + } |
| 65 | +) |
| 66 | + |
| 67 | +# Custom keys allowed because no semconv equivalent exists. Empty in the |
| 68 | +# scaffold — projects that extend this template add entries here as they |
| 69 | +# add custom span attributes (and constants in `src/observability/spans.py`). |
| 70 | +ALLOWED_CUSTOM_KEYS: frozenset[str] = frozenset() |
| 71 | + |
| 72 | +ACCEPTED_KEYS: frozenset[str] = SEMCONV_KEYS | ALLOWED_CUSTOM_KEYS |
| 73 | + |
| 74 | + |
| 75 | +@pytest.fixture |
| 76 | +def memory_exporter(monkeypatch: pytest.MonkeyPatch) -> InMemorySpanExporter: |
| 77 | + """Install a TracerProvider that records spans into an in-memory exporter. |
| 78 | +
|
| 79 | + Uses `monkeypatch.setattr` to swap `trace.get_tracer_provider` for the |
| 80 | + test's lifetime instead of `trace.set_tracer_provider` — the OTel SDK |
| 81 | + refuses to override the global provider once any other test has called |
| 82 | + `set_tracer_provider`, which would silently route spans to the wrong |
| 83 | + exporter. |
| 84 | +
|
| 85 | + Uses `SimpleSpanProcessor` so spans are visible to `get_finished_spans()` |
| 86 | + immediately after the span context exits — no flush race. |
| 87 | + """ |
| 88 | + exporter = InMemorySpanExporter() |
| 89 | + provider = TracerProvider() |
| 90 | + provider.add_span_processor(SimpleSpanProcessor(exporter)) |
| 91 | + monkeypatch.setattr(trace, "get_tracer_provider", lambda: provider) |
| 92 | + return exporter |
| 93 | + |
| 94 | + |
| 95 | +def _span_by_name(spans: Sequence[ReadableSpan], name: str) -> ReadableSpan: |
| 96 | + """Return the unique span with the given name (assert exactly one).""" |
| 97 | + matches = [s for s in spans if s.name == name] |
| 98 | + assert len(matches) == 1, ( |
| 99 | + f"expected exactly one span named {name!r}, got {len(matches)} " |
| 100 | + f"(all names: {[s.name for s in spans]})" |
| 101 | + ) |
| 102 | + return matches[0] |
| 103 | + |
| 104 | + |
| 105 | +def test_tool_call_span_carries_genai_tool_attributes( |
| 106 | + memory_exporter: InMemorySpanExporter, |
| 107 | +) -> None: |
| 108 | + """A tool-call span carries the documented `gen_ai.tool.*` keys.""" |
| 109 | + tool_attrs: dict[str, str | int] = { |
| 110 | + GENAI_TOOL_NAME: "echo", |
| 111 | + GENAI_TOOL_CALL_ARGUMENTS: '{"msg": "hi"}', |
| 112 | + GENAI_TOOL_CALL_RESULT: '{"echoed": "hi"}', |
| 113 | + } |
| 114 | + with agent_span("tool.echo", tool_attrs): |
| 115 | + pass |
| 116 | + |
| 117 | + spans = memory_exporter.get_finished_spans() |
| 118 | + tool_span = _span_by_name(spans, "tool.echo") |
| 119 | + assert tool_span.attributes is not None |
| 120 | + keys = set(tool_span.attributes) |
| 121 | + |
| 122 | + assert GENAI_TOOL_NAME in keys |
| 123 | + assert GENAI_TOOL_CALL_ARGUMENTS in keys |
| 124 | + assert GENAI_TOOL_CALL_RESULT in keys |
| 125 | + assert tool_span.attributes[GENAI_TOOL_NAME] == "echo" |
| 126 | + |
| 127 | + |
| 128 | +def test_llm_call_span_carries_genai_attributes( |
| 129 | + memory_exporter: InMemorySpanExporter, |
| 130 | +) -> None: |
| 131 | + """An LLM-style span carries the documented `gen_ai.*` keys + token usage.""" |
| 132 | + llm_attrs: dict[str, str | int] = { |
| 133 | + GENAI_CONVERSATION_ID: "session-test-1", |
| 134 | + GENAI_REQUEST_MODEL: "gpt-4o-mini", |
| 135 | + GENAI_OPERATION_NAME: "chat", |
| 136 | + GENAI_PROVIDER_NAME: "openai", |
| 137 | + GENAI_USAGE_INPUT_TOKENS: 42, |
| 138 | + GENAI_USAGE_OUTPUT_TOKENS: 100, |
| 139 | + } |
| 140 | + with agent_span("agent.llm_call", llm_attrs): |
| 141 | + pass |
| 142 | + |
| 143 | + spans = memory_exporter.get_finished_spans() |
| 144 | + llm_span = _span_by_name(spans, "agent.llm_call") |
| 145 | + assert llm_span.attributes is not None |
| 146 | + |
| 147 | + for key, value in llm_attrs.items(): |
| 148 | + assert key in llm_span.attributes, f"missing {key}" |
| 149 | + assert llm_span.attributes[key] == value |
| 150 | + |
| 151 | + |
| 152 | +def test_db_query_span_carries_db_attributes( |
| 153 | + memory_exporter: InMemorySpanExporter, |
| 154 | +) -> None: |
| 155 | + """A DB-query span carries `db.query.text` + `db.response.returned_rows`.""" |
| 156 | + db_attrs: dict[str, str | int] = { |
| 157 | + DB_QUERY_TEXT: "SELECT 1", |
| 158 | + DB_RESPONSE_RETURNED_ROWS: 1, |
| 159 | + } |
| 160 | + with agent_span("db.example_query", db_attrs): |
| 161 | + pass |
| 162 | + |
| 163 | + spans = memory_exporter.get_finished_spans() |
| 164 | + db_span = _span_by_name(spans, "db.example_query") |
| 165 | + assert db_span.attributes is not None |
| 166 | + keys = set(db_span.attributes) |
| 167 | + |
| 168 | + assert DB_QUERY_TEXT in keys |
| 169 | + assert DB_RESPONSE_RETURNED_ROWS in keys |
| 170 | + |
| 171 | + |
| 172 | +def test_no_unregistered_attribute_keys_emitted( |
| 173 | + memory_exporter: InMemorySpanExporter, |
| 174 | +) -> None: |
| 175 | + """Every emitted attribute key is in `SEMCONV_KEYS` or `ALLOWED_CUSTOM_KEYS`.""" |
| 176 | + with agent_span( |
| 177 | + "tool.echo", |
| 178 | + { |
| 179 | + GENAI_TOOL_NAME: "echo", |
| 180 | + GENAI_TOOL_CALL_ARGUMENTS: "{}", |
| 181 | + GENAI_TOOL_CALL_RESULT: "{}", |
| 182 | + }, |
| 183 | + ): |
| 184 | + pass |
| 185 | + |
| 186 | + spans = memory_exporter.get_finished_spans() |
| 187 | + |
| 188 | + rogue: list[tuple[str, str]] = [] |
| 189 | + for span in spans: |
| 190 | + if span.attributes is None: |
| 191 | + continue |
| 192 | + for key in span.attributes: |
| 193 | + if key not in ACCEPTED_KEYS: |
| 194 | + rogue.append((span.name, key)) |
| 195 | + |
| 196 | + assert not rogue, ( |
| 197 | + "Span attributes emitted with keys outside the documented registry: " |
| 198 | + f"{rogue}. Either use a semconv name from `src/observability/spans.py` " |
| 199 | + "or add the new key to both `spans.py` (with a comment explaining why " |
| 200 | + "no semconv equivalent applies) and `ALLOWED_CUSTOM_KEYS` in this test." |
| 201 | + ) |
| 202 | + |
| 203 | + |
| 204 | +def test_spans_module_constants_are_registered() -> None: |
| 205 | + """Every uppercase `str` constant in `spans.py` belongs to the test allowlist. |
| 206 | +
|
| 207 | + The allowlist is `SEMCONV_KEYS | ALLOWED_CUSTOM_KEYS`. Catches the |
| 208 | + "added a new constant in `spans.py` without updating the test" drift class. |
| 209 | + If this fails, either: |
| 210 | +
|
| 211 | + - the new constant is a semconv name → add it to `SEMCONV_KEYS`. |
| 212 | + - the new constant is a custom name → add it to `ALLOWED_CUSTOM_KEYS` |
| 213 | + AND ensure the comment in `spans.py` explains why no semconv applies. |
| 214 | + """ |
| 215 | + declared = { |
| 216 | + getattr(spans_module, name) |
| 217 | + for name in dir(spans_module) |
| 218 | + if name.isupper() and isinstance(getattr(spans_module, name), str) |
| 219 | + } |
| 220 | + unregistered = declared - ACCEPTED_KEYS |
| 221 | + assert not unregistered, ( |
| 222 | + f"`spans.py` defines constants not in the test allowlist: " |
| 223 | + f"{sorted(unregistered)!r}. Update `SEMCONV_KEYS` or " |
| 224 | + "`ALLOWED_CUSTOM_KEYS` in this test." |
| 225 | + ) |
0 commit comments