Skip to content

Retrieval and source identity

Retrieval is the center of ctxflow. With a retrieval span that lists what the vector store returned, and the source identity (C1) of each chunk, you unlock the Documents view, the chunks delivered to the model, the Never retrieved list and the lineage marks (C4, C6).

ctxflow reads the documents of a retrieval span in either convention:

Convention Attributes
OpenInference (openinference.span.kind=RETRIEVER) retrieval.documents.N.document.id, .content, .score, .metadata (a JSON string)
OTel GenAI gen_ai.retrieval.documents

Each document needs an id (the chunk id as your vector store holds it). A score is recommended: the turn detail shows it. The content is the chunk text, shown in the turn detail and used to match the chunk by hash. The metadata carries C1.

Set openinference.span.kind=RETRIEVER on a span with the OpenInference attributes: it is how that reading recognizes a retrieval. A manual retrieval span shows the keys you set when your code calls the vector store directly.

When the retrieval span ends, the SDK adds the identity of what the vector store returned, measured on that span, so before any reranker, compressor or snippet step:

Attribute Value
ctxflow.retrieval.item_ids Each item’s id: as stored in your vector store
ctxflow.retrieval.item_hashes Hash of each item’s text after Unicode NFC, whitespace runs as one space and trim: plain sha256
ctxflow.retrieval.item_verifiable false for an item with neither id nor text

You do not set these yourself. ctxflow joins each item to the chunk your ingestion wrote: by id, else by text hash. A retriever that wraps a compressor reports what it returns.

Each retrieved chunk should say which document it comes from and which state of it. Store these keys in the chunk metadata when you index, so the retriever returns them:

Key Meaning
ctxflow.source_id Stable id of the original document in its source system, for example its path relative to the document root. It must be the same in your ingestion and your retriever (how to choose it).
ctxflow.source_version The version in which the current content of the document first appeared. Your own label.
ctxflow.source_hash Hash of the original document as indexed, from ctxflow_otel.source_hash(original_bytes). Store it exactly as returned.

ctxflow_otel.source_hash(data) hashes the bytes as they are (a str as its UTF-8 bytes), with no normalization. The result is the plain sha256, 64 hex.

Rules that keep lineage correct:

  • Hash the original file bytes, not the parsed text or the chunk. Hashing something else makes every item look stale · hash_mismatch.
  • Give each version of a document its own source_version. Without a hash to compare, ctxflow compares versions; the constant unversioned proves nothing.

Without ctxflow.source_hash on the item or on the written chunk, C6 is unknown · no_item_hash. The ingestion extras stamp all three keys in the chunk metadata for you.

When your code calls the vector store itself (a function tool that runs vector_store.query(...), a custom retriever), no instrumentation makes the retrieval span: write it. These are the keys:

Attribute Value Needed
openinference.span.kind RETRIEVER Yes: without it ctxflow does not read the documents
retrieval.documents.N.document.id The chunk id as the vector store holds it Yes: the only key the chunk needs
retrieval.documents.N.document.score The retrieval score (a number) Recommended: shown in the turn detail
retrieval.documents.N.document.content The chunk text No, but without it the turn detail shows no chunk text and ctxflow cannot match the chunk by hash
retrieval.documents.N.document.metadata A JSON string with the C1 keys the chunk was indexed with No, but without it the chunk has no document and no version
input.value The query No

N counts from 0, one per returned chunk, in rank order. Name the span retrieval (ctxflow_semconv.RETRIEVAL_SPAN). The SDK adds the retrieval identity when the span ends.

import json
import ctxflow_semconv as sc
from opentelemetry import trace
tracer = trace.get_tracer("my-agent")
def search_documents(query: str) -> list[dict]:
hits = vector_store_query(query) # your call: [{"id", "text", "score", "metadata"}, ...]
with tracer.start_as_current_span(sc.RETRIEVAL_SPAN) as span:
span.set_attribute("openinference.span.kind", "RETRIEVER")
span.set_attribute("input.value", query)
for i, hit in enumerate(hits):
prefix = f"retrieval.documents.{i}.document"
span.set_attribute(f"{prefix}.id", hit["id"])
span.set_attribute(f"{prefix}.content", hit["text"])
span.set_attribute(f"{prefix}.score", hit["score"])
span.set_attribute(f"{prefix}.metadata", json.dumps(hit["metadata"]))
return hits

Call it from inside your tool function. If an instrumentation (LlamaIndex) already makes a retriever span, do not add this one: see LlamaIndex.

A runnable turn with a fake model: a root agent.turn, a retriever, a failing tool and a model call. It sends to whatever OTEL_EXPORTER_OTLP_ENDPOINT says.

import json
import ctxflow_otel
import ctxflow_semconv as sc
from opentelemetry import trace
from opentelemetry.trace import StatusCode
provider = ctxflow_otel.init()
tracer = trace.get_tracer("my-rag-agent")
# What your vector store returns: chunk id, chunk text and the C1 keys stored with the chunk.
# source_hash is computed at ingestion time from the original file bytes.
SHIPPING_MD = b"# Shipping\nShipping takes 3 to 5 days.\n"
HITS = [
{
"id": "kb-shipping-0",
"text": "Shipping takes 3 to 5 days.",
"score": 0.91,
"metadata": {
sc.SOURCE_ID: "kb/shipping.md",
sc.SOURCE_VERSION: "v3",
sc.SOURCE_HASH: ctxflow_otel.source_hash(SHIPPING_MD),
},
},
]
def retrieve(question: str) -> list[dict]:
with tracer.start_as_current_span(sc.RETRIEVAL_SPAN) as span:
span.set_attribute("openinference.span.kind", "RETRIEVER")
span.set_attribute("input.value", question)
for i, hit in enumerate(HITS):
meta = {k: v for k, v in hit["metadata"].items() if v is not None}
span.set_attribute(f"retrieval.documents.{i}.document.id", hit["id"])
span.set_attribute(f"retrieval.documents.{i}.document.content", hit["text"])
span.set_attribute(f"retrieval.documents.{i}.document.score", hit["score"])
span.set_attribute(f"retrieval.documents.{i}.document.metadata", json.dumps(meta))
return HITS
def order_status(order_id: str) -> str:
with tracer.start_as_current_span("execute_tool order_status") as span:
span.set_attribute("openinference.span.kind", "TOOL")
span.set_attribute(sc.TOOL_NAME, "order_status")
span.set_attribute("input.value", json.dumps({"order_id": order_id}))
span.set_status(StatusCode.ERROR, "order service down") # marks the failure
return "unknown"
def answer(question: str) -> str:
with tracer.start_as_current_span(sc.AGENT_TURN_SPAN) as turn: # one trace = one turn
turn.set_attribute("openinference.span.kind", "AGENT")
turn.set_attribute("input.value", question)
hits = retrieve(question)
order_status("A-1001")
with tracer.start_as_current_span("chat fake-model") as llm:
llm.set_attribute("gen_ai.operation.name", "chat") # marks a model call
llm.set_attribute("gen_ai.request.model", "fake-model")
llm.set_attribute("gen_ai.usage.input_tokens", 120)
llm.set_attribute("gen_ai.usage.output_tokens", 18)
reply = hits[0]["text"] # a real model would write the answer here
turn.set_attribute("output.value", reply) # plain-text answer, shown in the turn detail
return reply
with ctxflow_otel.conversation("conv-rag-1", user_id="u1", turn=0):
print(answer("How long does shipping take?"))
provider.shutdown()

What ctxflow gets from it:

  • The retrieval span with one item (S4), its C1 metadata (S5) and, added by the SDK, ctxflow.retrieval.item_ids and item_hashes (S6).
  • A tool call order_status with status ERROR: a tool_failed omission (S3).
  • A model call with tokens and model.
  • One chunk delivered to the model in the turn (Context delivered).

Using LlamaIndex or LangChain? The OpenInference instrumentation creates spans of this kind for you (Integrations). You add only the identity (ctxflow_otel.conversation(...)) and the C1 keys in your document metadata. For LlamaIndex retrievers see Retrievers and tools.

If the retrieval runs in an MCP server, the agent sees only the tool call and no chunks. Run the SDK in the server too and write the retrieval span there (above), so the chunks, their identity and the lineage marks come from the process that holds the vector store.

ctxflow.retrieval.tool=true is a narrow mark. It only applies to tool spans in the ctxflow shape (named agent.tool_call, tool.<name> or mcp.tool <name>, or carrying ctxflow.action.* keys), and it makes that tool call count as a retrieval call. It does not add chunks, and OpenInference TOOL spans and GenAI execute_tool spans ignore it. When a retrieval span is nested in the tool call, in the same process, the call counts as a retrieval call with no mark.