This specification is maintained by the AgentRules Working Group. Have enhancements or want to claim maintainership?Submit Specification →
devopscritical PriorityID: otel-v1-28-genai-span-redaction-standard

OpenTelemetry v1.28 GenAI Client-Side Ingress Span Redaction & Token Metrics Attribution

Enforces strict client-side PII/sensitive data redaction on GenAI spans adhering to OpenTelemetry Semantic Conventions v1.28 before telemetry egress. Mandates that prompt/completion payloads are sanitized in-process and token consumption attributes (gen_ai.usage.input_tokens, gen_ai.usage.output_tokens) are captured and attributed without data leakage.

Prohibited Anti-Pattern: Unsanitized GenAI prompt and completion capture leaking PII to telemetry collectors without token attribution

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: OpenTelemetry v1.28 GenAI Client-Side Ingress Span Redaction & Token Metrics Attribution - Enforces strict client-side PII/sensitive data redaction on GenAI spans adhering to OpenTelemetry Semantic Conventions v1.28 before telemetry egress. Mandates that prompt/completion payloads are sanitized in-process and token consumption attributes (gen_ai.usage.input_tokens, gen_ai.usage.output_tokens) are captured and attributed without data leakage.
globs: src/**/telemetry/**/*.{ts,js}, src/**/instrumentation/**/*.{ts,js}, src/**/llm/**/*.{ts,js}, src/**/ai/**/*.{ts,js}
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/otel-v1-28-genai-span-redaction-standard"
---

# OpenTelemetry v1.28 GenAI Client-Side Ingress Span Redaction & Token Metrics Attribution

> **Severity**: CRITICAL | **Category**: devops
> **Anti-Pattern Warning**: Unsanitized GenAI prompt and completion capture leaking PII to telemetry collectors without token attribution

## System Constraints
You are a Principal Engineer enforcing OpenTelemetry Semantic Conventions v1.28 GenAI Span Redaction Standard. Mandate that all spans matching GenAI semantic conventions (gen_ai.system, gen_ai.request.model, etc.) undergo deterministic, zero-allocation or streaming client-side token sanitization prior to recording span events or attributes. Raw prompts and completions must never leave the process memory unredacted. Token consumption metrics must be rigorously bound to standard OpenTelemetry v1.28 usage attributes at span termination.

## Strict Guidelines
- Engineers MUST ALWAYS sanitize raw user input and model output using an in-process redaction engine before assigning values to 'gen_ai.prompt' or span events.
- Engineers MUST NOT export raw conversational history, system prompts, or raw model completions directly to Span attributes or SpanProcessor queues.
- Code SHOULD enforce span attribute naming in strict alignment with OpenTelemetry GenAI Semantic Conventions v1.28 (e.g., 'gen_ai.system', 'gen_ai.request.model', 'gen_ai.usage.input_tokens', 'gen_ai.usage.output_tokens').
- Services MUST ensure that PII redaction logic handles edge cases such as SSNs, credit card numbers, email addresses, and bearer tokens deterministically before setting span status to OK.
- Components NEVER store unsanitized payload buffers in span attributes; if redaction fails, the attribute value must default to '[REDACTED_DUE_TO_ERROR]' rather than raw payload.

## Bad vs Good Implementations
### Client-Side Span Redaction and Token Attribution for GenAI LLM Calls

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Raw prompt and raw response payloads are piped directly into span attributes without PII redaction, causing high-risk data leakage to downstream trace backends. It also omits OpenTelemetry v1.28 semantic convention attributes for token usage.
```typescript
import { trace, SpanStatusCode } from '@opentelemetry/api';

const tracer = trace.getTracer('genai-service');

export async function executeGenAiCall(prompt: string, client: any) {
  return tracer.startActiveSpan('gen_ai.chat', async (span) => {
    try {
      // VIOLATION: Injecting raw unsanitized prompt directly into telemetry span
      span.setAttribute('gen_ai.prompt', prompt);
      span.setAttribute('gen_ai.system', 'openai');
      
      const response = await client.createCompletion({ prompt });
      
      // VIOLATION: Exporting raw completion without PII masking
      span.setAttribute('gen_ai.completion', response.choices[0].text);
      span.setStatus({ code: SpanStatusCode.OK });
      return response;
    } catch (error: any) {
      span.recordException(error);
      span.setStatus({ code: SpanStatusCode.ERROR, message: error.message });
      throw error;
    } finally {
      span.end();
    }
  });
}
```

#### Production Standard (Correct)
> **Standard**: Sanitizes prompt and completion strings prior to span emission, records sanitized telemetry via structured span events, and explicitly populates standard OpenTelemetry v1.28 token consumption attributes.
```typescript
import { trace, SpanStatusCode } from '@opentelemetry/api';

const tracer = trace.getTracer('genai-service', '1.28.0');

// Deterministic client-side redaction utility
function sanitizePii(payload: string): string {
  const emailRegex = /[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}/g;
  const ssnRegex = /\b\d{3}-\d{2}-\d{4}\b/g;
  const bearerRegex = /Bearer\s+[A-Za-z0-9\-_=.]+/g;
  return payload
    .replace(emailRegex, '[REDACTED_EMAIL]')
    .replace(ssnRegex, '[REDACTED_SSN]')
    .replace(bearerRegex, '[REDACTED_TOKEN]');
}

export async function executeGenAiCall(prompt: string, client: any) {
  return tracer.startActiveSpan('chat ' + client.modelName, async (span) => {
    try {
      span.setAttribute('gen_ai.system', 'openai');
      span.setAttribute('gen_ai.request.model', client.modelName);
      
      const sanitizedPrompt = sanitizePii(prompt);
      // OTel v1.28 compliant span event with sanitized content
      span.addEvent('gen_ai.content.prompt', {
        'gen_ai.prompt': sanitizedPrompt
      });

      const response = await client.createCompletion({ prompt });
      const choice = response.choices?.[0]?.text ?? '';
      const sanitizedCompletion = sanitizePii(choice);

      span.addEvent('gen_ai.content.completion', {
        'gen_ai.completion': sanitizedCompletion
      });

      // OTel v1.28 token usage metrics attribution
      if (response.usage) {
        span.setAttribute('gen_ai.usage.input_tokens', response.usage.prompt_tokens);
        span.setAttribute('gen_ai.usage.output_tokens', response.usage.completion_tokens);
      }

      span.setStatus({ code: SpanStatusCode.OK });
      return response;
    } catch (error: any) {
      span.recordException(error);
      span.setStatus({ code: SpanStatusCode.ERROR, message: error.message });
      throw error;
    } finally {
      span.end();
    }
  });
}
```

Architectural Specification & Invariant Rationale

Architectural Invariant Design: OpenTelemetry v1.28 GenAI Client-Side Ingress Span Redaction & Token Metrics Attribution

OpenTelemetry v1.28 GenAI Client-Side Ingress Span Redaction & Token Metrics Attribution defines an industrial-grade behavioral standard for devops engineering. Enforces strict client-side PII/sensitive data redaction on GenAI spans adhering to OpenTelemetry Semantic Conventions v1.28 before telemetry egress. Mandates that prompt/completion payloads are sanitized in-process and token consumption attributes (gen_ai.usage.input_tokens, gen_ai.usage.output_tokens) are captured and attributed without data leakage. Modern software architectures require strict adherence to deterministic patterns to guarantee high availability, maintainability, and zero security vulnerabilities.

Framework Paradigm Shift & Drift MechanicsLLMs are trained on millions of open-source repositories containing outdated code, legacy idioms, and unpatched antipatterns. When coding assistants generate implementations for this stack, they default to common statistical tokens: Unsanitized GenAI prompt and completion capture leaking PII to telemetry collectors without token attribution Without an explicit system instruction file, developers spend hours debugging silent failures.
Failure Modes & Production Blast Radius

Hazard Analysis: What Breaks Without This Rule

The following failure modes have been cataloged from hundreds of hours of production code reviews where AI assistants produced non-compliant implementations:

Failure ModeAI Symptom (The Anti-Pattern)SeverityProduction Impact & Remedy
AI Hallucination & Deprecation DriftUnsanitized GenAI prompt and completion capture leaking PII to telemetry collectors without token attributionCritical
Violating this industrial standard introduces regression bugs, security risks, and unexpected runtime failures in production.
Enforce explicit behavioral system directives across all AI coding assistants in your repository.
Silent Architecture InconsistencyAI assistants produce mixed paradigms across files, creating fragmented codebase conventions.Medium
Increases cognitive load during code reviews and leads to maintenance debt across engineering teams.
Pin project conventions in .cursor/rules, CLAUDE.md, and AGENTS.md so all team agents follow identical guardrails.
Architectural Directives in Detail

Step-by-Step Production Directives

Each rule constraint below is injected into the AI agent's system prompt to establish deterministic boundaries:

1

Engineers MUST ALWAYS sanitize raw user input and model output using an in-process redaction engine before assigning values to 'gen_ai.prompt' or span events.

Engineers MUST ALWAYS sanitize raw user input and model output using an in-process redaction engine before assigning values to 'gen_ai.prompt' or span events.

Rationale:AI models frequently generate unconstrained code here because statistical language distributions lack project-specific architectural context. Mandating this directive ensures that generated code adheres to verified industrial production requirements.
Enforcement:Integrated into the Agent Pack rule file. When Cursor, Claude Code, or Codex processes this prompt, it applies this constraint before emitting syntax.
2

Engineers MUST NOT export raw conversational history, system prompts, or raw model completions directly to Span attributes or SpanProcessor queues.

Engineers MUST NOT export raw conversational history, system prompts, or raw model completions directly to Span attributes or SpanProcessor queues.

Rationale:AI models frequently generate unconstrained code here because statistical language distributions lack project-specific architectural context. Mandating this directive ensures that generated code adheres to verified industrial production requirements.
Enforcement:Integrated into the Agent Pack rule file. When Cursor, Claude Code, or Codex processes this prompt, it applies this constraint before emitting syntax.
3

Code SHOULD enforce span attribute naming in strict alignment with OpenTelemetry GenAI Semantic Conventions v1.28 (e.g., 'gen_ai.system', 'gen_ai.request.model', 'gen_ai.usage.input_tokens', 'gen_ai.usage.output_tokens').

Code SHOULD enforce span attribute naming in strict alignment with OpenTelemetry GenAI Semantic Conventions v1.28 (e.g., 'gen_ai.system', 'gen_ai.request.model', 'gen_ai.usage.input_tokens', 'gen_ai.usage.output_tokens').

Rationale:AI models frequently generate unconstrained code here because statistical language distributions lack project-specific architectural context. Mandating this directive ensures that generated code adheres to verified industrial production requirements.
Enforcement:Integrated into the Agent Pack rule file. When Cursor, Claude Code, or Codex processes this prompt, it applies this constraint before emitting syntax.
4

Services MUST ensure that PII redaction logic handles edge cases such as SSNs, credit card numbers, email addresses, and bearer tokens deterministically before setting span status to OK.

Services MUST ensure that PII redaction logic handles edge cases such as SSNs, credit card numbers, email addresses, and bearer tokens deterministically before setting span status to OK.

Rationale:AI models frequently generate unconstrained code here because statistical language distributions lack project-specific architectural context. Mandating this directive ensures that generated code adheres to verified industrial production requirements.
Enforcement:Integrated into the Agent Pack rule file. When Cursor, Claude Code, or Codex processes this prompt, it applies this constraint before emitting syntax.
5

Components NEVER store unsanitized payload buffers in span attributes

Components NEVER store unsanitized payload buffers in span attributes; if redaction fails, the attribute value must default to '[REDACTED_DUE_TO_ERROR]' rather than raw payload.

Rationale:AI models frequently generate unconstrained code here because statistical language distributions lack project-specific architectural context. Mandating this directive ensures that generated code adheres to verified industrial production requirements.
Enforcement:Integrated into the Agent Pack rule file. When Cursor, Claude Code, or Codex processes this prompt, it applies this constraint before emitting syntax.
Technical Questions & Answers

Frequently Asked Technical Questions

Common questions developers face when configuring AI coding assistants for this stack:

Q:Why is OpenTelemetry v1.28 GenAI Client-Side Ingress Span Redaction & Token Metrics Attribution critical for AI coding assistants?

Enforces strict client-side PII/sensitive data redaction on GenAI spans adhering to OpenTelemetry Semantic Conventions v1.28 before telemetry egress. Mandates that prompt/completion payloads are sanitized in-process and token consumption attributes (gen_ai.usage.input_tokens, gen_ai.usage.output_tokens) are captured and attributed without data leakage. Without explicit behavioral boundaries, AI coding assistants (Cursor, Claude Code, Windsurf, Codex) rely on training data averages, which frequently produce deprecated, inefficient, or vulnerable code patterns.

Q:How does adopting this rule prevent AI hallucinations?

This rule explicitly declares what the AI must avoid (Unsanitized GenAI prompt and completion capture leaking PII to telemetry collectors without token attribution) and prescribes verified positive examples. Grounding the LLM with negative and positive pairs eliminates guesswork.

Q:Which AI coding environments are supported?

This specification is multi-platform compatible: Cursor (.cursor/rules/*.mdc & .cursorrules), Anthropic Claude Code (CLAUDE.md), Windsurf (.windsurfrules), Codex / Cline (AGENTS.md), and GitHub Copilot (.github/copilot-instructions.md).

Q:Can I combine this rule with other technology stacks?

Yes. Use the Interactive Stack Builder or download an Agent Pack to merge this rule with other frontend, backend, database, security, and DevOps rules without syntax collision.

Open Specification · CC BY 4.0·Free for Personal, Team & Commercial In-Repo Use

Citation & Open Source Attribution Guidelines

This specification is licensed under Creative Commons Attribution 4.0 International (CC BY 4.0). You are completely free to adapt and share this rule in your workspace. If citing, including in public AI benchmark datasets, or redistributing, attribution to AgentRules.org is required.

1 Rule in Stack

OpenTelemetry