標準に従ってスパンに名前を付ける
読了まで約40 分。8 節に5 例を収録。
Labs
この章を実際に手を動かして学ぶ
すべての例を書籍どおりに実行し、コードを変更して結果を確認し、書籍のコードとデータに自分のアイデアを試せる。インストールは不要で、作業内容は保存される。約 30 秒で開く。
すべての例を書籍どおりに実行し、コードを変更して結果を確認し、書籍のコードとデータに自分のアイデアを試せる。インストールは不要で、作業内容は保存される。Labs が実行環境を用意する: 月40 時間。
自分のマシンで、無料: 書籍のノートブックをダウンロード、そのコードとデータを GitHub から取得する。
書籍のバージョンでコードを実行する
この章を終えると、アシスタントのトレースに含まれる各スパンに、OpenTelemetry の GenAI 規約がそのステップに対して求める名前、種別、属性を与えられるようになる。また、どのソフトウェアがそのスパンを生成したか、名前がどのスキーマバージョンに従っているかを示せるようになる。さらに、スパンがレジストリから外れたときに失敗するチェックを実行できるようになる。
Ambrewick のオンコールエンジニアは、本書がトレースを構築する対象のアシスタントを運用している(1 件のメッセージ、1 件のトレース)。彼らは、そのトレースを自分たちがすでに運用しているツールで扱いたいと考えている。それらのツールが知っている語彙は一つだけであり、モデル呼び出し、検索、ツール実行、エージェントのターンに対して規約が与える名前である。第 1 章の名前は、そこでは何の意味も持たない。この章で構築するチェックであるバリデータは、各スパンをレジストリの規則と照合する。デバイスに関する質問で検索を含むメッセージ 809 に対して実行すると、4 個のスパンから 4 件の指摘が出る。指摘はスパンごとに 1 件であり、いずれも、そのスパンには既知のスパン種別がないと述べている。SDK はどの名前も受け付けるため、SDK はこれらの指摘を一つも出さなかった。そこでこの章では、各スパンに標準の名前と種別を与え、誰がそれを生成したかを記録し、名前を正しく保つチェックを構築する。続く第 3 章では、クライアントライブラリのスパンをこれらの名前に照らして測定する。
Development 版の標準
バックエンドは、スパンに関する問い合わせを名前で処理する。今週のモデル呼び出しにどれだけ時間がかかったかという問いは、どのスパンがモデル呼び出しであるかについてすべてのバックエンドが合意している場合にのみ、一つの答えを持つ。標準とは、その合意のことである。セマンティック規約とは、スパン、属性、メトリクスに対して公開された名前、型、意味の取り決めであり、どのバックエンドも同じ名前を同じように読み取れるようにするものである。ここでの標準は、OpenTelemetry の GenAI セマンティック規約である。
GenAI の名前は、当初 OpenTelemetry のコアのセマンティック規約リポジトリに置かれていた。そのリポジトリはリリース 1.42.0 で gen_ai プレフィックスの名前を非推奨とし、名前は独立したリポジトリへ移った(変更履歴)。本書は、そのリポジトリの最初の単独リリースである GenAI 規約のバージョン 0.1.0 に従う(変更履歴)。
規約には二つの形式がある。人が読むためのページと、プログラムが読めるレジストリである。レジストリは、スパンの種類、その kind、属性を記述した YAML モデルである。本書の検証ツールは、固定されたバージョンのレジストリを読む。したがって、検証ツールが確認する名前は、レジストリに載っている名前である。
GenAI 規約のバージョン 0.1.0 のすべてのページは Development であり、その名前はどのリリースでも変更される可能性がある。仕様は自らの構成要素について Development を定義しており、そのステータスのページは、そうした構成要素について次のように述べている。「The component MAY be removed without prior notice. The component SHOULD NOT be used in production.」(ステータスのページ)。GenAI のページも同じステータスを持ち、その変更履歴には名前の変更が示されている。最初の単独リリースでは、推論スパンの種類の名前が gen_ai.inference.client から gen_ai.client.inference に変更された。本書の名前はそのリリースに従っているため、後のリリースで名前が変更される可能性がある。
実践ルール: 公開するすべての名前の横に、規約のバージョンを固定して記載すること。Development の名前の上に構築したダッシュボードには、名前が変更されたときに実行される検査が必要である。
この部分はまだ翻訳されていないため、英語で表示している。
Span types for each step
The registry sorts spans into span types, and each type has a name pattern, a span kind and the attributes it requires. Chapter 1's steps fall into four of them. An inference span is the span of one client call to a generative model that answers the prompt or asks for a tool call. A retrieval span is the span of one run of the application's retrieval step, which returns the documents relevant to a query. A tool-execution span is the span of one run of a tool, named for the tool. An agent-invocation span is the span of one invocation of an agent. The book's agent runs in the assistant's process, so its span is the in-process type, which also covers workflows. A remote agent's span is a CLIENT span of its own type. The route and answer steps are model calls, the retrieve step is a search, the tool runs are tool runs, and each message's root is one agent run.
| Span type | Name pattern | Kind | Operation name |
|---|---|---|---|
| Inference | {operation} {model} |
CLIENT, or INTERNAL in process | chat |
| Retrieval | {operation} |
INTERNAL | retrieval |
| Tool execution | execute_tool {tool} |
INTERNAL | execute_tool |
| Agent invocation | invoke_agent {agent} |
INTERNAL in process; CLIENT for a remote agent | invoke_agent |
1"""Print the span name each step gets from the assistant, beside the registry's pattern for that span type. The names are2the spans', the patterns are the registry's, and each assert checks one span's name against its pattern.34The point rests on the four name lines: the inference, tool and agent names from message 11159 (a route, an answer, a5tool call and a second answer), and the retrieval name from message 809."""6from lib.assistant import Assistant7from lib.bm25 import Retriever8from lib.case import load_articles, load_messages, load_tool_durations9from lib.clock import VirtualClock10from lib.dayrun import DAY, RECORDING, RELEASE11from lib.export import spans_to_rows12from lib.genai import REGISTRY_VERSION, SCHEMA_URL, SPAN_OPERATIONS, SPAN_TYPES13from lib.ids import SequentialIds14from lib.replay import Replay, ReplayContacts15from lib.tools import Tools16from lib.tracing import make_provider17from opentelemetry.sdk.trace.export.in_memory_span_exporter import InMemorySpanExporter1819replay = Replay(RECORDING)20retriever, tools = Retriever(load_articles(), RELEASE.top_k), Tools(load_tool_durations(), ReplayContacts(replay))21rows = {}22for message in (m for m in load_messages(DAY) if m.message_id in ("809", "11159")):23 clock, exporter = VirtualClock(DAY, start_ns=message.arrival_ns), InMemorySpanExporter() # one exporter per message24 tracer = make_provider("ambrewick-assistant", RELEASE.service_version, "dev-day-replay", clock, SequentialIds(),25 exporter, SCHEMA_URL).get_tracer("ambrewick.assistant", schema_url=SCHEMA_URL)26 Assistant(replay, retriever, tools, clock, tracer, RELEASE).handle(message)27 rows[message.message_id] = spans_to_rows(exporter)28agent = next(row for row in rows["11159"] if row["parent_span_id"] is None) # the root is the agent's invocation29inference = next(row for row in rows["11159"] if row["attributes"].get("gen_ai.operation.name") == "chat")30tool = next(row for row in rows["11159"] if row["attributes"].get("gen_ai.operation.name") == "execute_tool")31retrieval = next(row for row in rows["809"] if row["attributes"].get("gen_ai.operation.name") == "retrieval")32print("GenAI conventions version:", REGISTRY_VERSION)33print("inference span name:", inference["name"])34print("retrieval span name:", retrieval["name"])35print("tool span name:", tool["name"])36print("agent span name:", agent["name"])37print("inference provider name:", inference["attributes"]["gen_ai.provider.name"])38print("inference prompt name:", inference["attributes"]["gen_ai.prompt.name"])39print("inference prompt version:", inference["attributes"]["gen_ai.prompt.version"])40# Model spans are `{operation} {model}`, retrieval is its operation alone, tools are `execute_tool {tool}`, the agent is41# `invoke_agent {agent}`. Each assert checks one span against its pattern.42assert inference["name"] == f"chat {RELEASE.model}" and retrieval["name"] == "retrieval"43assert tool["name"] == f"execute_tool {tool['attributes']['gen_ai.tool.name']}"44assert agent["name"] == f"invoke_agent {agent['attributes']['gen_ai.agent.name']}"45for span_type in sorted(SPAN_OPERATIONS): # the operation names the registry defines, per span type46 print(f"operation names, {span_type}:", ", ".join(SPAN_OPERATIONS[span_type]))47for span_type in sorted(SPAN_TYPES): # the attributes the validator requires, per span type48 print(f"required attributes, {span_type}:", len(SPAN_TYPES[span_type]["required"]))
python inference-span-names.pyGenAI conventions version: 0.1.0
inference span name: chat qwen3-4b-instruct-2507
retrieval span name: retrieval
tool span name: execute_tool remove_item
agent span name: invoke_agent ambrewick-assistant
inference provider name: openai
inference prompt name: ambrewick.route
inference prompt version: p1
operation names, gen_ai.client.inference: chat, generate_content, realtime_inference, text_completion
operation names, gen_ai.execute_tool: execute_tool
operation names, gen_ai.invoke_agent.internal: invoke_agent
operation names, gen_ai.retrieval: retrieval
required attributes, gen_ai.client.inference: 2
required attributes, gen_ai.execute_tool: 2
required attributes, gen_ai.invoke_agent.internal: 1
required attributes, gen_ai.retrieval: 1
required attributes, mcp.client: 1
required attributes, mcp.server: 1
モデルスパンの名前にはプロバイダではなくモデルを使う
+10 件の検証Span types for each step、2章よりもう一度読む
attributeを基にする。1章「スパンを手作業で作る」より
spanを基にする。1章「1メッセージにつき1トレース」より
この演習が扱った内容は新版で変わった。2026.11.2版で変わった点
42行目は、モデルスパンの名前をモデルではなくプロバイダ属性から作っている。42行目を修正し、モデルスパンが、そのレジストリのパターンに対して、実行で使われたモデルを用いて照合されるようにせよ。
仕組み
ツール名とエージェント名の検査を書く
+10 件の検証Span types for each step、2章よりもう一度読む
attributeを基にする。1章「スパンを手作業で作る」より
spanを基にする。1章「1メッセージにつき1トレース」より
この演習が扱った内容は新版で変わった。2026.11.2版で変わった点
例では 43 行目と 44 行目が空白である。属性 gen_ai.tool.name と gen_ai.agent.name を使い、ツールスパンの名前とエージェントスパンの名前を、それぞれのレジストリパターンと照合する assert を 2 つ書く。
仕組み
検索スパンの名前にインデックスが含まれない理由
+10 件の検証Span types for each step、2章よりもう一度読む
spanを基にする。1章「1メッセージにつき1トレース」より
この演習が扱った内容は新版で変わった。2026.11.2版で変わった点
この例は、検索がナレッジベースに対して実行されるにもかかわらず、"retrieval span name: retrieval" と出力する。インデックスを含まない名前を説明するのはどれか。
仕組み
The model span changes most. Its name is the operation, a space, and the model's name, so a reader scanning a trace sees which model answered each call. Message 11159, a lists request with one tool call, has its first model call named chat qwen3-4b-instruct-2507. The registry gives one list of well-known values for gen_ai.operation.name on an inference span, and a custom value MAY be used beyond it (registry attributes). The validator maps each value to a span type through a map the book makes, and that map gives the inference type chat, generate_content, realtime_inference, text_completion. The assistant writes chat for each of its calls. The example asserts the model span's name against the operation and the model the run used, and it builds the tool and agent names from the attributes their spans carry, so a drift in either one fails the run.
The retrieval span is named by its operation alone, retrieval. The registry's pattern leaves no room for the index it searched, so the knowledge base's name stays out of the span name. A tool run is named for its tool, execute_tool remove_item, the run of the list tool that removed an item in message 11159. The root is named invoke_agent ambrewick-assistant, and it replaces chapter 1's message span. We keep invoke_agent rather than invoke_workflow, because the model chooses the route and whether to call a tool. The model drives the control flow through tool calls, which is the case the registry's agent type describes.
One attribute the registry leaves open is the provider. In the book, the inference span's gen_ai.provider.name is openai, and that value is our judgement. The registry's well-known values for the attribute include no value for llama.cpp, and a provider the list lacks may take a custom value (registry). The attribute's general note says it "SHOULD be set based on the instrumentation's best knowledge and may differ from the actual upstream provider" (client inference). We record openai because Ambrewick's client speaks OpenAI's API to its endpoint, and the official package records openai for that call, as chapter 3 shows. A reader whose model is served another way should choose by the same rule and say so.
Of the spans the assistant makes, the fallback span is the only one the registry does not name. The book keeps it, the validator flags it, and the validation section says why that flag is the right answer.
Working rule: Name each span from its registry pattern, not from the function that made it, and take the operation name from the registry's well-known values. Where the registry gives no value for something you run, use the value the client and its official instrumentation would write, and say that it's a judgement.
スパンの種別はプロセスに従う
スパンの種別は、その処理がどこで実行されたかを示す。プロセスの外へ出る呼び出しには CLIENT、受け取る呼び出しには SERVER、プロセス内部の処理には INTERNAL を用いる(このほかに PRODUCER と CONSUMER があり、キューに渡される処理を表す)。難しいのはモデル呼び出しの場合である。レジストリには次のようにある。「計装対象の GenAI システムが通常はクライアントとは別のプロセスで動作する場合、または GenAI 呼び出しが HTTP などの計装済みプロトコルを介して行われる場合は、CLIENT 種別を用いることを推奨する」(client inference)。エンドポイントの背後にあるモデルへは、アシスタントのプロセスの外へ出る呼び出しで到達するため、そのスパンは CLIENT になる。レジストリは、同じプロセス内で動作するモデルに INTERNAL を用いることも認めており、そのため種別の決定には判断が伴う。本書は、スパン自体が示せる検証、すなわちその呼び出しがサーバーを名指ししているかどうかで、この規則を適用する。サーバーを名指しする呼び出しは CLIENT であり、何も名指ししない呼び出しは INTERNAL でよい。
1"""Give one model call two kinds: CLIENT when the model sits behind an endpoint, as the trace shows it, and INTERNAL2when the same assistant runs the model in process. Then run the validator on both.34The point rests on the two model-call kind lines and on the zero findings: the registry allows INTERNAL for an5in-process model (it says MAY), and the validator accepts it when the call names no server. An endpoint span marked6INTERNAL is flagged, because it names one."""7from lib.dayrun import DAY, RECORDING, run_day_traced8from lib.genai import REGISTRY_VERSION, validate9from lib.replay import Replay101112class InProcess:13 """The recorded model, run as if it shared the assistant's process: the same answers, and no endpoint."""1415 in_process = True1617 def __init__(self, replay):18 self._replay = replay1920 def reply(self, request):21 return self._replay.reply(request)222324rows = run_day_traced(DAY, ["809"], live=False).spans # a devices message: a route and an answer call, behind an endpoint25local = run_day_traced(DAY, ["809"], backend=InProcess(Replay(RECORDING)), live=False).spans # the same model in process26endpoint = next(row for row in rows if row["name"].startswith("chat "))27in_process = next(row for row in local if row["name"].startswith("chat "))28retrieval = next(row for row in rows if row["name"] == "retrieval")29root = next(row for row in rows if row["parent_span_id"] is None)30marked = dict(endpoint, kind="INTERNAL") # the endpoint's span, wrongly marked as in process3132print("GenAI conventions version:", REGISTRY_VERSION)33print("model call kind, behind an endpoint:", endpoint["kind"])34print("model call kind, in process:", in_process["kind"])35address, port = endpoint["attributes"]["server.address"], endpoint["attributes"]["server.port"]36print("server the endpoint span names:", f"{address}:{port}")37print("findings on the in-process span:", len(validate(in_process)))38print("findings on the endpoint span marked INTERNAL:", len(validate(marked)))39print("retrieval span kind:", retrieval["kind"])40print("agent span kind:", root["kind"])41assert validate(endpoint) == [] and validate(in_process) == [] # both kinds are the registry's42assert "server.address" not in in_process["attributes"] # an in-process model names no server43assert len(validate(marked)) == 1 and "kind is INTERNAL" in validate(marked)[0]44assert validate(retrieval) == [] and validate(root) == [] # INTERNAL is the registry's kind for these two types
python span-kinds-by-process.pyGenAI conventions version: 0.1.0
model call kind, behind an endpoint: CLIENT
model call kind, in process: INTERNAL
server the endpoint span names: localhost:8000
findings on the in-process span: 0
findings on the endpoint span marked INTERNAL: 1
retrieval span kind: INTERNAL
agent span kind: INTERNAL
メッセージ 809 のモデル呼び出しを両方の方法で実行すると、この規則の働きが分かる。メッセージ 809 は、ルート呼び出しと回答呼び出しを持つ devices の質問である。エンドポイントの背後では、スパンの種別は CLIENT であり、同じ呼び出しをプロセス内で実行すると INTERNAL になる。エンドポイントのスパンはサーバーを名指ししており、プロセス内のスパンは何も名指ししていない。バリデータは、プロセス内のスパンについて 0 件の指摘を報告する。この件数は例の中でアサートされている。エンドポイントのスパンを INTERNAL とした場合でも、そのスパンはサーバーを名指ししたままであり、バリデータはそれについて 1 件の指摘を報告する。指摘の文面には種別 kind is INTERNAL が含まれることがアサートされており、出力されるのは件数のみである。この指摘が、規則によって防ごうとしている不具合である。
本書の dev-day のトレースはすべて CLIENT である。記録されたモデル呼び出しが、エンドポイントを介して処理されたためである。プロセス内のケースは、同じモデルをアシスタント自身のコードから呼び出すものであり、本書ではこの例の中でのみ実行する。モデルをプロセス内へ移す読者は、それに伴って種別が変わることを想定すべきであり、スパンがなおサーバーを名指ししている場合には、バリデータがそれを指摘することを想定すべきである。
検索スパンとエージェントスパンはどちらも INTERNAL である。どちらの処理もアシスタントの内部で実行されるためで、例の中でそれぞれについてアサートされている。出力される種別は、検索スパンが INTERNAL、エージェントスパンが INTERNAL である。レジストリは両方の種別を定めており(registry)、バリデータがそれらを検査する。
実践ルール: 呼び出しがサーバーへ向かう場合は、同じマシン上のサーバーであっても、モデルのスパンに CLIENT を与える。INTERNAL を与えるのは、モデルが自分のプロセス内で動作し、かつスパンがサーバーを名指ししない場合に限る。設定した各種別は、バリデータに検査させる。
スパンが持たなければならない属性
名前は、スパンが何であるかをバックエンドに伝える。要件レベルは、そのスパンがどの属性を持たなければならないかを伝える。要件レベルは、属性がいつ現れなければならないかを定めるものであり、必須、条件付き必須、推奨、オプトインの四つがある(要件レベル)。必須属性は、その種類のすべてのスパンに現れる。条件付き必須の属性は、条件が成り立つときに現れ、レジストリは条件を属性の横に記している。推奨属性は、良いスパンが何を持つかを示し、オプトインの属性は、何かがそれを有効にしたときにだけ現れる。
レジストリは、各スパンの種類がどの属性を持たなければならないかも定めている。本書のモジュール lib.genai はレジストリのすべての要件レベルを保持している。したがって、バリデータが検査する要件レベルと種類は、誰かが手で入力した一覧ではなく、レジストリのものである。バリデータが検査するのは種類と必須属性だけである。そのため、スパンはバリデータを通過しても、条件付きの場合にレジストリが求める属性を欠いていることがある。inference-span-names の例が出力するバリデータの件数は、各スパンの種類が要求する数を示している。推論スパンでは 2、ツール実行スパンでは 2、検索スパンでは 1、エージェントスパンでは 1 である。その必須属性は操作名とプロバイダ名であり、したがってプロバイダの判断は省略できない。どちらか一方でも欠くスパンは、検査に失敗する。
プライバシーの観点で注意すべきなのは、オプトインの属性である。モデル呼び出しのメッセージ内容はオプトインであるため、本書のスパンは、スイッチで求めない限りそれらを一切持たない。そのスイッチが何をするかは第3章で述べる。
バリデータが読まないのは、条件付きの要件である。gen_ai.prompt.version は、スパンが gen_ai.prompt.name を持ち、かつバージョンが利用できる場合に、推論スパンで条件付き必須となる。gen_ai.prompt.name は、名前付きのプロンプトテンプレートを使う場合に条件付き必須となる(レジストリ)。アシスタントのプロンプトには名前とバージョンが付いているため、その推論スパンは両方を持つ。メッセージ 11159 のルート呼び出しでは ambrewick.route と p1 がそれである。第10章では、このペアを問い合わせてリリースを区別する。バリデータは必須属性だけを読むので、どちらかを欠くスパンがあっても報告しない。条件付き属性の欠落は、バリデータが報告しない欠落である。
実践ルール: スパンの名前を読む前に、そのスパンの要件レベルを読むこと。必須属性の欠落は、スパンの欠陥である。条件付き必須属性の欠落は、その条件が成り立つときにだけ欠陥となる。したがって、報告する前にレジストリで条件を確認すること。
スパンを作ったのは誰か
スパンは何を計測したかを示し、誰が計測したかは別の二つの場所が示す。リソースとインストルメンテーションスコープである。インストルメンテーションスコープは、スパンを作ったコードの単位に名前を付けるものであり、通常はインストルメンテーションライブラリを指す。ここではアシスタント自身のモジュールである。スキーマ URL は、公開されたテレメトリスキーマ、すなわちテレメトリが従うセマンティック規約のリリースに名前を付ける。本文ではスキーマ URL を直接記さない。ここに示す URL はいずれも、対応する例が出力したものである。
リソースには、本書が自ら設定する三つの属性がある。service.name は ambrewick-assistant である。service.version は 1.0.0 であり、リリースを示す。第10章では、これを読んでトレースをリリースごとに分割する。service.instance.id は dev-day-replay である。リプレイはインスタンス ID を自ら設定するため、再実行しても同じインスタンスの名前が使われ、実行ごとにトレースを比較できる。再起動するプロセスがインスタンス ID を保てるのは、ID が明示的に設定されていた場合に限られる。再起動をまたいで一つのインスタンスを追跡するクエリには、ID が変わらないことが必要である。
1"""Print the resource and the instrumentation scope of the renamed spans, with the schema URL each one carries, beside2chapter 1's stamp.34The point rests on the schema lines: chapter 1's resource said 1.44.0, the renamed spans say 1.45.0, and the SDK's5constants have no 1.45.0 schema, which the assert checks. The book takes that URL from the registry's manifest6(genai.SCHEMA_URL), and make_provider puts it on the tracer as well as the resource."""7from lib.dayrun import RELEASE8from lib.genai import SCHEMA_URL9from lib.ids import SequentialIds10from lib.tracing import make_provider, span11from opentelemetry.sdk.trace.export.in_memory_span_exporter import InMemorySpanExporter12from opentelemetry.semconv.schemas import Schemas1314CHAPTER_1_SCHEMA = "https://opentelemetry.io/schemas/1.44.0"151617def version_key(url):18 """Sort key for a schema URL: its version as numbers, so 1.9 sorts before 1.44."""19 return tuple(int(part) for part in url.rsplit("/", 1)[1].split("."))202122exporter = InMemorySpanExporter()23provider = make_provider("ambrewick-assistant", RELEASE.service_version, "dev-day-replay", None, SequentialIds(),24 exporter)25tracer = provider.get_tracer("ambrewick.assistant") # no schema given: the tracer carries the provider's26span(tracer, "resource probe", 1, 2) # one ended span, so the scope's schema can be read from it27scope = exporter.get_finished_spans()[0].instrumentation_scope28chapter_1 = make_provider("ambrewick-assistant", RELEASE.service_version, "dev-day-replay", None, SequentialIds(),29 InMemorySpanExporter(), CHAPTER_1_SCHEMA) # the resource chapter 1 built, read back from it30known = {schema.value for schema in Schemas} # what opentelemetry-semantic-conventions 0.66b2 can stamp31print("chapter 1's resource schema URL:", chapter_1.resource.schema_url)32print("renamed spans' resource schema URL:", provider.resource.schema_url)33print("renamed spans' scope schema URL:", scope.schema_url)34print("instrumentation scope name:", scope.name)35print("highest schema in the SDK's constants:", max(known, key=version_key))36print("service.name:", provider.resource.attributes["service.name"])37print("service.version:", provider.resource.attributes["service.version"])38print("service.instance.id:", provider.resource.attributes["service.instance.id"])39assert SCHEMA_URL not in known # the constants stop at 1.44.0, so the book takes its 1.45.0 from the registry40assert provider.resource.schema_url == scope.schema_url == SCHEMA_URL41assert provider.resource.attributes["service.instance.id"] == "dev-day-replay" # set, not drawn at random
python resource-and-schema.pychapter 1's resource schema URL: https://opentelemetry.io/schemas/1.44.0
renamed spans' resource schema URL: https://opentelemetry.io/schemas/1.45.0
renamed spans' scope schema URL: https://opentelemetry.io/schemas/1.45.0
instrumentation scope name: ambrewick.assistant
highest schema in the SDK's constants: https://opentelemetry.io/schemas/1.44.0
service.name: ambrewick-assistant
service.version: 1.0.0
service.instance.id: dev-day-replay
スキーマ URL をレジストリから取得する理由
+10 件の検証出力では、名前を変更したスパンに、SDK の定数の中で最も新しいものよりも新しいスキーマ URL が付与されている。この例が、その URL を定数からではなくレジストリのマニフェストから取得しているのはなぜか。
仕組み
本章ではスキーマ URL が変わった。例は両方の値を出力する。第1章のリソースは https://opentelemetry.io/schemas/1.44.0 としていた。これは、固定したセマンティック規約パッケージ 0.66b2 が持つ最新のスキーマであり、そのパッケージの最上位のスキーマは https://opentelemetry.io/schemas/1.44.0 である。第1章の名前はどの規約にも従っていなかったため、そのスタンプは本書のスパンが述べる内容を何も表していなかった。名前を改めたスパンは https://opentelemetry.io/schemas/1.45.0 をスタンプする。これは、GenAI 規約 v0.1.0 が依存するコアのセマンティック規約のリリースである。GenAI 規約は v0.1.0 の時点では独自のスキーマ URL を公開していない。コアは、gen_ai.* の名前が独自のリポジトリに移された 1.42.0 で、それらを非推奨とした。したがってスタンプが示すのは、リソースの service.* の名前がどのコアのリリースに従うかであり、GenAI のバージョンは検証と並べて 0.1.0 として持ち回る。本書の生成モジュールはこの URL をレジストリのマニフェストから取得し、例は SDK の定数にこの URL が含まれないことをアサートする。定数は、その SDK 自身のリリースで止まっている。service.* 属性のうち、この URL が指すリリースが非推奨とするのは service.peer.name と service.peer.namespace だけである(変更履歴)。そのため、リソースが設定する三つの属性は、どちらの URL でも同じ意味に読める。
名前を改めたスパンのインストルメンテーションスコープは ambrewick.assistant であり、そのスキーマ URL はリソースのものと同じである。例はこれをアサートする。公式クライアントライブラリは独自のスコープを書き込む。
実践ルール: リソースには service.name と service.version を自分で設定し、service.instance.id にはインスタンスごとに一意の値を与える。これは本番環境の節で説明するとおりである。そのうえで、トレーサーには、依存するコアのリリースのスキーマ URL を与える。取得元は、規約より遅れることがある SDK の定数ではなく、レジストリのマニフェストとする。GenAI 規約のバージョンは、検証ツールと並べて固定する。v0.1.0 にはスタンプすべきスキーマ URL がないためである。
レジストリに対する検証
名前はレジストリに関する主張であり、バリデータはその主張を検証可能にする。バリデータは、各スパンの型を gen_ai.operation.name から見つける。MCP スパンの場合は、そのメソッドから見つける。MCP は Model Context Protocol であり、ツールサーバーが用いるプロトコルである。次にバリデータは、スパンの種別と必須属性をレジストリの規則に照らして検査する。型を見つけられないスパンには、その旨を示す指摘が付く。各指摘は対象のスパンを名指しするので、出力は修正すべき項目の一覧として読める。
バリデータは第1章のスパンを名指しできない。それらのスパンには、型を見つけるために読む属性である gen_ai.operation.name がないからである。メッセージ 809 の 4 個のスパンは message、route、retrieve、answer であり、検査はそれぞれに 1 件ずつ指摘を出力する。その内容は no known span type for this row である。指摘が理由を示している。ルートの名前を変更すると、message は invoke_agent ambrewick-assistant になり、そのスパンは自身の型に対して検査される。
1"""Run the validator over chapter 1's rough spans for message 809: every span fails, because none names a registry span2type.34The point rests on the count of findings, one per span, and on the text of each: "no known span type" means the span5carries neither `gen_ai.operation.name` nor an MCP method, which is how the validator finds a registry span's type."""6from lib.dayrun import RELEASE, run_dev_day7from lib.export import spans_to_rows8from lib.genai import REGISTRY_VERSION, validate9from lib.ids import SequentialIds10from lib.report import fmt_int11from lib.tracing import make_provider, span12from opentelemetry.sdk.trace.export.in_memory_span_exporter import InMemorySpanExporter1314# Chapter 1 stamped this schema; kept so the spans are the ones chapter 1 printed.15CHAPTER_1_SCHEMA = "https://opentelemetry.io/schemas/1.44.0"1617(run,) = run_dev_day(["809"]) # message 809: a route call, a retrieval, and an answer call18outcome = run.outcome19exporter = InMemorySpanExporter()20provider = make_provider("ambrewick-assistant", RELEASE.service_version, "dev-day-replay", run.clock, SequentialIds(),21 exporter, CHAPTER_1_SCHEMA)22tracer = provider.get_tracer("ambrewick.assistant")23# Chapter 1's names: the root is the message, each step is named by its step, and no kind is set (INTERNAL).24root = span(tracer, "message", run.arrived_ns, run.replied_ns,25 attributes={"ambrewick.route": outcome.route, "ambrewick.reply.source": outcome.source})26for step in outcome.steps:27 attributes = {"ambrewick.step": step.step}28 if step.step in ("route", "answer"): # model calls carry their token counts, under the book's own keys29 attributes |= {"ambrewick.tokens.input": step.prompt_tokens, "ambrewick.tokens.cached": step.cached_tokens,30 "ambrewick.tokens.output": step.completion_tokens}31 span(tracer, step.step, step.start_ns, step.end_ns, parent=root, attributes=attributes)3233rows = spans_to_rows(exporter) # sorted by (trace, start, span), so the findings print in the same order every run34findings = [finding for row in rows for finding in validate(row)]35print("GenAI conventions version:", REGISTRY_VERSION)36print("spans checked:", fmt_int(len(rows)))37for finding in findings:38 print("finding:", finding)39print("findings, no known span type:", fmt_int(sum("no known span type" in finding for finding in findings)))40print("findings, all:", fmt_int(len(findings)))41assert all(len(validate(row)) == 1 for row in rows) # each span fails once, and only once
python validate-the-spans.pyGenAI conventions version: 0.1.0
spans checked: 4
finding: message: no known span type for this row
finding: route: no known span type for this row
finding: retrieve: no known span type for this row
finding: answer: no known span type for this row
findings, no known span type: 4
findings, all: 4
第1章のスパンに型がない理由
+10 件の検証メッセージ 809 のすべてのスパンが「no known span type for this row」と出力する。その理由を述べている文はどれか。
仕組み
名前を変更すると、スパンは検査に通る。この例は、開発日の全 20 件のメッセージにわたって 74 個のスパンを検査し、レジストリが定義するスパンについては 0 件の問題を見つける。1 つのアサーションがこの件数を 0 に保つので、名前を壊す変更は、新しい数値を出力するのではなく、実行を失敗させる。
1"""Run the validator over every span of the dev day's twenty messages: no finding on any span the registry defines, and2one on each of the book's own fallback spans, which the registry does not define.34The point rests on the line "findings on registry spans: 0", which is asserted, and on the fallback count, which5equals the fallback replies."""6from lib.assistant import Assistant7from lib.bm25 import Retriever8from lib.case import load_articles, load_messages, load_tool_durations9from lib.clock import VirtualClock10from lib.dayrun import DAY, RECORDING, RELEASE11from lib.export import spans_to_rows12from lib.genai import REGISTRY_VERSION, SCHEMA_URL, validate13from lib.ids import SequentialIds14from lib.replay import Replay, ReplayContacts15from lib.report import fmt_int16from lib.tools import Tools17from lib.tracing import make_provider18from opentelemetry.sdk.trace.export.in_memory_span_exporter import InMemorySpanExporter19from collections import Counter2021replay = Replay(RECORDING)22retriever, tools = Retriever(load_articles(), RELEASE.top_k), Tools(load_tool_durations(), ReplayContacts(replay))23messages, fallback_replies, rows = load_messages(DAY), 0, []24for message in messages: # arrival order, as the replay needs; each message gets its own clock, exporter and trace25 clock = VirtualClock(DAY, start_ns=message.arrival_ns)26 exporter = InMemorySpanExporter() # one per message, so each message's IDs start from 127 tracer = make_provider("ambrewick-assistant", RELEASE.service_version, "dev-day-replay", clock, SequentialIds(),28 exporter, SCHEMA_URL).get_tracer("ambrewick.assistant", schema_url=SCHEMA_URL)29 fallback_replies += Assistant(replay, retriever, tools, clock, tracer, RELEASE).handle(message).source == "fallback"30 rows += spans_to_rows(exporter)3132book = [row for row in rows if row["name"] == "ambrewick.fallback"]33# The book's own fallback span is not a registry span, so it is checked apart from the others.34registry_findings = [finding for row in rows if row["name"] != "ambrewick.fallback" for finding in validate(row)]35book_findings = [finding for row in book for finding in validate(row)]36# A span with no gen_ai.operation.name is counted under its own name, which is how the fallback span appears.37operations = Counter(row["attributes"].get("gen_ai.operation.name", row["name"]) for row in rows)38print("GenAI conventions version:", REGISTRY_VERSION)39print("messages:", fmt_int(len(messages)))40print("spans checked:", fmt_int(len(rows)))41for operation in sorted(operations):42 print(f"spans, {operation}:", fmt_int(operations[operation]))43print("findings on registry spans:", fmt_int(len(registry_findings)))44print("fallback replies:", fmt_int(fallback_replies))45print("findings on the book's fallback span:", fmt_int(len(book_findings)))46assert not registry_findings # zero findings on every span the registry defines47assert len(book_findings) == len(book) == fallback_replies # one per fallback span, and each span is a fallback reply48assert all("no known span type" in finding for finding in book_findings)
python validate-the-renamed-spans.pyGenAI conventions version: 0.1.0
messages: 20
spans checked: 74
spans, ambrewick.fallback: 6
spans, chat: 37
spans, execute_tool: 3
spans, invoke_agent: 20
spans, retrieval: 8
findings on registry spans: 0
fallback replies: 6
findings on the book's fallback span: 6
バリデータは、ほかのスパンには指摘を出す。6 件のフォールバック応答にはそれぞれ ambrewick.fallback スパンがあり、検査はその 6 件すべてに、それぞれ no known span type という指摘を付ける。これは正しい動作であり、規約の失敗ではない。レジストリは、名前を挙げた型だけを定義しており、それ以外のスパンには型がない。本書独自のスパンと属性は、本書の名前空間である ambrewick. に置かれる。命名規則も、名前を名前空間の中に置くよう求めている(命名規則)。スパンがレジストリの外にあるという指摘は、そのスパンが本書独自のものであることを示している。各指摘はこの指摘であって他のものではないことがアサートされるので、レジストリのスパンに指摘が付けば、実行は失敗する。
実践ルール: レジストリのスパンに対する指摘は、欠陥として読む。自分の名前空間のスパンに対する指摘は、そのスパンが自分のものであるというレジストリの回答として読む。
本番環境でスパンに名前を付ける
ここでの検証器は、例の中で記録済みのスパンに対して動作する。本番環境では、サービスが実際にエクスポートするスパンに対して同じ検査を実行する必要がある。ただし、この検査が気づかれないまま失敗する原因が三つある。さらに四つ目の原因が、インスタンス ID に意味があるかどうかを左右する。本番環境で Development の名前を使うことを推奨するのは、その名前が固定され、かつ検証されている場合である。アップグレード後の検証器の初回実行が、何が変わったかを示すからである。
一つ目は名前の内容である。仕様は、スパン名がそのスパンの種類に対して「最も一般的な文字列」であることを求めており、get_account/42 は具体的すぎる例として挙げている(span API)。モデルスパンの名前には、短い固定リストの中から選んだモデルが入る。これは十分に一般的である。ユーザー ID から組み立てた名前はユーザーごとに新しい名前となるが、レジストリのパターンには識別子を入れる余地がない。スパン名に識別子が含まれているのをレビュアーが見つけた場合は、検証器の結果にかかわらず、それを欠陥として扱うべきである。
二つ目は SDK である。SDK は誤った名前を止めない。第 1 章の大まかな名前はそのまま通過したし、レジストリ名のつづりを誤った場合も同様に通過する。レジストリを読むのは検証器だけであり、検証器を実行せずにスパンをエクスポートするパイプラインには、検査がまったくないことになる。検証器はテストだけでなく、スパンをエクスポートするパイプラインでも実行することを推奨する。
三つ目はアップグレードである。Development の名前は、どのリリースでも変更されうる。アップグレード後の検証器の初回実行では、変わったものが一覧に出る。固定されたバージョンを変更する前にその一覧を読み、名前の変更はバージョンの変更と同じプルリクエストで行う。古い名前を書き出す別のパッケージのスパンが、同じバックエンドに届くこともある。それらと本書のスパンを保持するバックエンドでは、一つのステップに二つの語彙が現れる。
四つ目はインスタンス ID である。service.namespace、service.name、service.instance.id の三つ組は、グローバルに一意でなければならない(MUST)(service registry)。SDK の既定値は、プロセスごとに新しくランダムに生成される UUID である。本番環境ではそのランダムな UUID を使い続けるか、インスタンス固有の ID から UUIDv5 を導出する。一つの値を複数のレプリカで共有してはならない。リプレイで使う固定のインスタンス ID は、リプレイでは正しいが、そのまま真似るのは誤りである。
スパンを追加するときは、レジストリの種別、名前、種類の順に書く。この順序を推奨するのは、種別が名前のパターンと種類を決めるからである。
実践ルール: スパンをエクスポートするパイプラインで検証器を実行し、指摘があればビルドを失敗させる。規約のバージョンは検査と並べて固定し、そのバージョンを上げる前に変更履歴を読む。
この章で決めたこと
レジストリは変わっていくものであり、名前もそれに伴って変わる。この章で確定させるのは、本書のスパンがどのバージョンに従うかということと、スパンがそれに従わなくなったときに報告する検査である。以下の各項目は、本書の以降の部分が前提とする選択であり、例はそれぞれについて、検証できるものを表明している。
- 本書の名前は GenAI conventions 0.1.0 に従う。レジストリは Development の段階にあるため、このバージョンはバリデータと並べて固定する。
- 検索スパンは、操作名のみの
retrievalと名付ける。レジストリのパターンには、それ以外のものを入れる場所がないためである。 - プロバイダの値は
openaiとする。これは本書の判断であり、レジストリの指針を並べて引用してある。レジストリには llama.cpp と照合できる値がないため、バリデータはこれを検査できない。 - アシスタントのプロンプトには名前とバージョンを付ける。そのため、推論スパンは
gen_ai.prompt.nameをgen_ai.prompt.versionとともに持つ。レジストリは、この組を条件付きで必須としている。 - モデルスパンの種別はプロセスの構成に従う。サーバの背後にある場合は CLIENT とし、スパンがサーバを名指ししない、プロセス内のみの場合に限って INTERNAL とする。
- 本書のリソースとトレーサは、SDK の最新の定数ではなく、レジストリが依存するコアリリースのスキーマ URL を持つ。
- バリデータは、レジストリ上のスパンに対する指摘を欠陥として報告する。本書独自のフォールバックのスパンには、それ専用の指摘を出すが、それらは欠陥ではない。
この版における本章
第2026.11.2版2026年11月23日時点で例が通過この章の5 例件のうち5件が合格
英語版の書籍(版2026.11.2)から翻訳した。