Designing a Data Boundary for Production AI Telemetry
Build AI telemetry that preserves operational visibility while controlling content export through validated metadata, scoped capture budgets, and payload-level tests.
On this page
A production AI service needs enough telemetry to explain latency, spend, failed tools, and unexpected workflow paths. It rarely needs every document fragment or user message in the same searchable system.
I would treat telemetry export as a data contract with a specific destination, approved fields, and enforced failure behavior. A debugging flag can request additional visibility, but it should not expand that contract on its own.
Consider a hypothetical product-matching assistant that compares supplier catalogues. Engineers need to distinguish slow retrieval from model retries and invalid product matches. Supplier pricing, unpublished product descriptions, and contact details may also pass through the model. Those inputs belong to the application’s data boundary even when an instrumentation library calls them span attributes.
Decide what each destination may receive
Start by separating operational telemetry from diagnostic content. Operational records describe execution: approved route identifiers, bounded operation types, elapsed time, normalized outcomes, and usage counts. Diagnostic artifacts may contain selected source material and require a separate access and lifecycle policy.
That separation is an architectural choice. OpenTelemetry’s GenAI span conventions currently describe instructions, inputs, and outputs as content that instrumentation should not capture by default. They also describe storing content externally with references on spans. These are convention recommendations, not proof of what an installed SDK actually emits.
Define a destination matrix before configuring exporters:
| Destination | Typical approved data | Additional controls |
|---|---|---|
| Operational monitoring | Validated counts, timings, route and outcome enums | Restricted dimensions, retention, access review |
| Diagnostic artifact store | Explicitly selected, minimized content | Scoped capture authorization, encryption, expiry, access audit |
| Evaluation dataset | Reviewed cases and expected behavior | Dataset approval, provenance, independent retention |
| Billing or audit system | Required usage or decision records | Its own durable contract and access policy |
An operational trace should not automatically become a training or evaluation record. Copying data between these destinations is another release decision.
My distributed tracing article covers span structure and token-cost visibility. This article concentrates on the boundary that determines which data can enter those systems.
Inventory the whole telemetry envelope
Deleting a prompt attribute is a useful local action, but it does not establish that an export is free of content. An exception might include the request body; a tool span name might include a product description; a log body might serialize the entire state object.
Review every surface that can carry data:
| Surface | Example risk | Boundary rule |
|---|---|---|
| Span attributes | Messages or arbitrary tool arguments | Explicit field and value contract |
| Events and log bodies | Full request or response objects | Separate schema; no unrestricted object serialization |
| Exceptions and status descriptions | SDK error containing source content | Normalized error category instead of raw text |
| Span and event names | User-controlled identifiers or text | Names from a static vocabulary |
| Resource, scope, and link attributes | Customer labels, custom context | Review these maps independently |
| HTTP and database instrumentation | URLs, headers, query parameters, query text | Instrumentation-specific minimization and validation |
| Baggage and other propagation | Context forwarded beyond the service | Outbound propagation policy independent of export |
OpenTelemetry’s baggage documentation warns that sensitive baggage can reach third-party services and has no built-in integrity checks. Baggage is also distinct from span attributes. Removing exported attributes therefore cannot replace controls on outbound request headers. Never use a baggage value as authority to enable diagnostic capture.
Do this inventory for direct vendor exporters, application logs, crash reporters, local console exporters, and framework callbacks. A centrally configured Collector only governs traffic that actually reaches it.
Construct operational records from approved values
For application-owned telemetry, I prefer a positive projection: construct a new record containing the facts the monitoring destination is allowed to receive. That gives unknown fields no automatic route to export.
The TypeScript example below operates on a decoded data object. It validates string values against a bounded vocabulary, validates numeric counters, and never spreads the original object into its output. The attribute names are an application-specific example, not a replacement definition of OpenTelemetry’s GenAI conventions.
type SafeRecord = Readonly<{ name: "app.ai.call"; attributes: Readonly<Record<string, string | number>>;}>;const operations = new Set(["answer", "retrieve", "tool_read"]);const routes = new Set(["catalog_assistant", "docs_assistant"]);const outcomes = new Set(["ok", "timeout", "denied", "error"]);function member(value: unknown, allowed: ReadonlySet<string>): value is string { return typeof value === "string" && allowed.has(value);}function count(value: unknown): value is number { return typeof value === "number" && Number.isSafeInteger(value) && value >= 0;}// Input is a decoded data object, not an arbitrary object with getters.function projectTelemetry( candidate: Readonly<Record<string, unknown>>,): SafeRecord | null { if (!member(candidate.operation, operations) || !member(candidate.route, routes) || !member(candidate.outcome, outcomes) || !count(candidate.durationMs)) { return null; } const attributes: Record<string, string | number> = { "app.telemetry.policy_version": "ops-v1", "app.ai.operation": candidate.operation, "app.ai.route": candidate.route, "app.ai.outcome": candidate.outcome, "app.ai.duration_ms": candidate.durationMs, }; if (count(candidate.inputTokens)) { attributes["app.ai.input_tokens"] = candidate.inputTokens; } if (count(candidate.outputTokens)) { attributes["app.ai.output_tokens"] = candidate.outputTokens; } return Object.freeze({ name: "app.ai.call", attributes: Object.freeze(attributes), });}A string-shaped value is not automatically appropriate metadata. A field named route can still leak content if arbitrary text is accepted. The fixed route and outcome vocabularies are therefore part of the contract, not merely convenient TypeScript types.
This function produces a small operational DTO. It is not an OTLP exporter and does not sanitize every span generated elsewhere in the process. A real integration must map the approved fields into the telemetry SDK and account for any resource attributes, events, or automatic exception handling that the SDK adds. If the existing span contains unreviewed fields, adding this DTO beside it does not make that span safe.
Keep measurement sources trustworthy as well. Numeric validation does not prove that a count came from the provider rather than user input. The adapter should obtain usage from validated provider responses and elapsed time from application measurements.
Avoid recording raw exceptions in this path. Translate known failures into categories such as timeout, denied, or error, and maintain any necessary detailed diagnostic separately. The older tracing examples are a starting point for instrumentation; error messages and stack traces need the same data review as explicit prompt fields.
Place enforcement before copies accumulate
The strongest minimization happens before sensitive content enters a telemetry object. Disable unnecessary content capture at the instrumentation source and inspect effective configuration, including framework wrappers and vendor extensions.
Then apply an additional export policy at a controlled boundary. OpenTelemetry’s sensitive-data guidance recommends collecting only what serves an observability purpose and reviewing emitted instrumentation data. It describes Collector processors as tools for additional filtering and transformation.
The Collector redaction processor supports allowed attribute keys and blocked-value handling. Treat that as a documented component capability, not a universal envelope guarantee. Validate the exact component version, signal type, and covered fields. Attribute filtering alone does not establish policy coverage for names, bodies, nested content, or every automatic event.
Place the relevant filtering before batching or persistent export queues whenever the topology permits. Otherwise the unfiltered payload may already exist in buffers, queue files, or a failed-export archive. A downstream filter cannot undo a previous copy.

*Flow: operational telemetry is projected and filtered before monitoring export. Any detailed diagnostic capture follows a separate scoped authorization and restricted storage path.*
Restrict network routes and exporter credentials so an unreviewed direct exporter cannot silently bypass the controlled path. Apply equivalent ownership to logs and crash reporting. Review enrichment after filtering too: a later processor must not reattach the data that an earlier stage removed.
Authorize diagnostic capture with an expiring budget
Some failures require inspecting content. Make that a scoped operation with an accountable owner and a specific purpose. A capture authorization should bind the tenant, workflow, diagnostic case, selected fields, expiry, and record and byte limits. A global environment flag is too broad to express that contract.
The following Python example demonstrates budget reservation within one process. The grant registry comes from a trusted control service, the scope comes from authenticated application context, and time comes from a trusted clock. None of these values should be accepted from a model response or propagated baggage.
from dataclasses import dataclass, replacefrom threading import Lock@dataclass(frozen=True)class Scope: tenant: str workflow: str case_id: str@dataclassclass Grant: scope: Scope expires_at_ms: int fields: frozenset[str] remaining_records: int remaining_bytes: int revoked: bool = Falseclass CaptureBudget: """Single-process illustration; the grants come from a trusted service.""" def __init__(self, grants: dict[str, Grant]): self._grants = {key: replace(value) for key, value in grants.items()} self._lock = Lock() def revoke(self, grant_id: str) -> None: with self._lock: grant = self._grants.get(grant_id) if grant is not None: grant.revoked = True def reserve( self, grant_id: str, scope: Scope, requested_fields: frozenset[str], payload_bytes: int, now_ms: int, ) -> bool: if (type(payload_bytes) is not int or payload_bytes <= 0 or type(now_ms) is not int or now_ms < 0 or not requested_fields): return False with self._lock: grant = self._grants.get(grant_id) if (grant is None or grant.revoked or grant.scope != scope or now_ms >= grant.expires_at_ms or not requested_fields <= grant.fields or grant.remaining_records < 1 or grant.remaining_bytes < payload_bytes): return False grant.remaining_records -= 1 grant.remaining_bytes -= payload_bytes return TrueReserve against the serialized, minimized payload’s UTF-8 byte size before storing it. Counting characters is not equivalent to counting stored bytes. Define whether the budget includes envelope overhead and enforce that same definition at the storage boundary.
The lock protects only callers sharing this Python instance. A multi-worker deployment needs a shared atomic conditional update or transaction to prevent overspending. Bind capture attempts to an idempotency key so retries cannot create unbounded duplicate artifacts. Failed storage may consume the reservation; conservative underuse is preferable to accidentally bypassing the cap.
A reservation is also not indefinite permission to write. The artifact service should recheck the grant’s version, expiry, and revocation state at the commit boundary. Define how revocation affects in-flight writes and how already committed artifacts are handled. Keep artifact access and deletion auditable.
Store opaque references in traces only when the destination is allowed to receive them. An identifier can still reveal relationships, and a presigned download URL is a capability, not a harmless identifier. The viewer must authorize access on each request; knowing a trace ID or artifact ID should not grant content access.
Specify how the boundary fails
Telemetry problems should have predictable outcomes. If a required field fails validation, drop that operational record or map it to an approved minimal error record. Do not log the rejected object to explain the rejection.
When diagnostic authorization is expired, unavailable, revoked, or exhausted, deny content capture while allowing approved operational metadata to continue. A capture-control outage should not turn into permission to capture everything. An application may have separate mandatory audit requirements; those records need their own durability behavior rather than relying on sampled monitoring.
Bound buffers and queues. If the monitoring destination is unavailable, apply an explicit drop or bounded buffering policy and count the losses. If a local queue can contain content, protect it as a content store with appropriate permissions, encryption where required, and expiry. Do not route failed exports to an unrestricted fallback sink.
Sampling controls volume, not permission. A sampled record can still contain an entire private document. Tail-sampling systems may also receive data before deciding what to retain, so inspect the actual placement of the content boundary.
Pattern matching is useful as a secondary detector for recognized secrets. It cannot identify every sensitive business fact or contextual disclosure. Likewise, hashing a predictable identifier can preserve linkability and may allow guessing the original value. The destination decision must consider meaning and access, not just whether a value looks redacted.
Test the bytes that reach each destination
Unit tests should establish the projection contract, including rejected enum values, invalid numeric fields, and unknown content fields. Test diagnostic authorization for scope mismatch, expiry, revocation, record exhaustion, byte exhaustion, and concurrent reservations.
Those tests are necessary but do not prove the behavior of the full telemetry pipeline. Add an integration harness that runs the actual pinned instrumentation, processors, and exporters against a local test receiver. Use synthetic canary strings instead of real customer records.
Place distinct canaries in prompts, tool arguments, tool results, exceptions, event names, log bodies, resource attributes, and relevant HTTP context. Exercise success, timeout, retry, cancellation, streaming, and exporter-failure paths. Inspect the payload at every external destination and any persistence layer that can hold records before export.
Assert both confidentiality and utility: prohibited canaries must be absent, while approved timing, outcome, and usage fields must remain usable. A filter that exports nothing may satisfy one negative test while making the service impossible to operate. Add explicit coverage for diagnostics that are denied and diagnostics that are legitimately granted.
Run the harness when changing instrumentation dependencies, exporter topology, or the data contract. Keep content fixtures separate from ordinary CI logs and ensure failed assertions do not print entire payloads. This complements LLM regression gates with a deterministic test of data flow.
Operate the policy as a production component
Useful measurements include rejected-record counts by bounded reason, unknown-field counts without raw key names, export failures, queue occupancy, dropped records, active capture grants, denied capture attempts, reserved diagnostic bytes, and artifacts past their deletion deadline. Measure access to diagnostic artifacts separately from artifact creation.
Do not turn a policy metric into another disclosure channel. Avoid customer names, arbitrary keys, artifact IDs, or exception text in metric labels. Investigate individual cases through access-controlled audit records.
Set retention independently for monitoring, diagnostic artifacts, evaluation datasets, backups, and export queues. Expiring a capture grant stops future collection; it does not delete existing data. Artifact lifecycle jobs should remove content and track failures. Coordinate any required deletion in external destinations and derived copies through their supported mechanisms rather than assuming a trace deletion covers everything.
There are trade-offs. A strict field contract requires maintenance and may omit useful diagnostics. Separate artifact storage adds authorization and lifecycle work. Minimization can make a rare incident harder to investigate. In return, routine monitoring remains useful without creating a broadly searchable duplicate of application content.
Start with synthetic reproduction and operational metadata, then grant narrowly scoped content access when the investigation needs it. Keep the boundary aligned with application egress controls, and use restricted diagnostic material to build replay fixtures only after a separate review.
Primary sources and topic provenance
- OpenTelemetry: GenAI client span conventions.
- OpenTelemetry: Handling sensitive data.
- OpenTelemetry: Baggage.
- OpenTelemetry Collector: Redaction processor.
Topic discovery: Viral Ruparel’s Your Agent Traces Are Shipping Customer Prompts to Your Observability Vendor, published October 15, 2026 on the reference site. The catalogue scenario, destination contract, examples, and diagram here were developed independently.
KEEP READING
Related engineering notes
A Failover Route Is Not a Recovery Path: Proving Independence in AI Infrastructure
Two LLM providers can share the same failure domain. Build an evidence-backed recovery graph that checks cloud, networking, identity, control-plane and capacity dependencies before admitting fallback routes, then test correlated outages without weakening safety.
Read articleAn Eval Platform Sunset Can Erase Your Release Evidence: Build an Evidence-Escrow Migration Gate
When a hosted LLM evaluation platform retires, switching runners is not enough. Preserve the historical evidence, reconstruct grader semantics, validate scoring parity, and enforce a fail-closed release gate that survives the service shutdown.
Read articleWhen the Package Runs Before Your App: Quarantining AI Framework Releases
The 2026 agent-framework PyPI compromise exposed a blind spot in AI build pipelines: Python startup hooks execute before application imports. Design an artifact-quarantine gate, inspect wheels without installing them, separate credentials, and recover from suspected exposure.
Read article