This specification is maintained by the AgentRules Working Group. Have enhancements or want to claim maintainership?Submit Specification →
devopscritical PriorityID: otel-genai-semantic-conventions-leak-guardrail

OpenTelemetry GenAI Semantic Conventions and Context Leak Guardrail

Enforces strict OpenTelemetry GenAI semantic conventions across agentic LLM workflows while preventing PII and confidential context exfiltration through telemetry span attributes. Requires token budget accounting, cryptographic payload hashing over raw prompt injection, and normalized metric dimensions across distributed inference meshes.

Prohibited Anti-Pattern: Raw Prompt Exfiltration and Unstandardized Telemetry in GenAI Traces

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: OpenTelemetry GenAI Semantic Conventions and Context Leak Guardrail - Enforces strict OpenTelemetry GenAI semantic conventions across agentic LLM workflows while preventing PII and confidential context exfiltration through telemetry span attributes. Requires token budget accounting, cryptographic payload hashing over raw prompt injection, and normalized metric dimensions across distributed inference meshes.
globs: src/**/telemetry/**/*.{ts,js}, src/**/llm/**/*.{ts,js}, src/**/agents/**/*.{ts,js}, src/**/instrumentation/**/*.{ts,js}
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/otel-genai-semantic-conventions-leak-guardrail"
---

# OpenTelemetry GenAI Semantic Conventions and Context Leak Guardrail

> **Severity**: CRITICAL | **Category**: devops
> **Anti-Pattern Warning**: Raw Prompt Exfiltration and Unstandardized Telemetry in GenAI Traces

## System Constraints
You are a Principal Software Architect enforcing OpenTelemetry GenAI Semantic Conventions and zero-trust telemetry guardrails. Mandate that all LLM interactions emit standardized `gen_ai.*` attributes. Never permit raw prompt texts, system instructions, or unredacted tool inputs/outputs to be attached to spans as open attributes. Enforce token budget tracking, deterministic prompt hashing for trace correlation, and span status alignment with OpenTelemetry standards.

## Strict Guidelines
- Engineers MUST ALWAYS populate standard OpenTelemetry GenAI attributes (`gen_ai.system`, `gen_ai.request.model`, `gen_ai.operation.name`, `gen_ai.usage.input_tokens`, `gen_ai.usage.output_tokens`).
- Engineers MUST NOT serialize raw prompt strings, system context, or raw completion payloads into span attributes (`gen_ai.prompt`, `gen_ai.completion`) unless explicit cryptographic differential privacy or PII-redacted scrubbing pipelines are invoked and configured.
- Code SHOULD generate a deterministic SHA-256 fingerprint (`gen_ai.prompt.fingerprint`) of prompt templates and system directives to allow trace grouping without exfiltrating confidential tenant data.
- Services MUST record token usage counters and track token budget ceiling violations by setting span status to `StatusCode.ERROR` when inference limits or context token budgets are exceeded.
- Components NEVER capture sensitive tool execution outputs (such as credentials, API keys, or raw SQL results) inside agent telemetry attributes; payload metadata must be limited to sanitised schema descriptions and execution status.

## Bad vs Good Implementations
### Agentic LLM Instrumentation with Sanitization & Semantic Conventions

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Raw user queries and system instructions are written directly to span attributes without redaction or hashing, exfiltrating sensitive context and user PII to telemetry sinks (e.g., Datadog, Honeycomb). In addition, attributes use non-standard keys (`tokens`, `prompt.system`) instead of official OpenTelemetry GenAI semantic conventions, breaking cross-service aggregations and cost analysis.
```typescript
import { trace } from '@opentelemetry/api';

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

export async function executeAgentStep(systemPrompt: string, userQuery: string, llmClient: any) {
  return tracer.startActiveSpan('llm-inference', async (span) => {
    try {
      // VIOLATION: Raw prompt and user PII exfiltrated into telemetry backend
      span.setAttribute('prompt.system', systemPrompt);
      span.setAttribute('prompt.user', userQuery);

      const response = await llmClient.complete({ prompt: `${systemPrompt}\n${userQuery}` });

      // VIOLATION: Non-standard attribute names and raw text emission
      span.setAttribute('response.output', response.text);
      span.setAttribute('tokens', response.tokensUsed);

      return response;
    } finally {
      span.end();
    }
  });
}
```

#### Production Standard (Correct)
> **Standard**: Adheres strictly to OpenTelemetry GenAI semantic conventions (`gen_ai.system`, `gen_ai.request.model`, `gen_ai.usage.input_tokens`, `gen_ai.usage.output_tokens`). Sensitive prompt context is cryptographically hashed via SHA-256 fingerprints to prevent telemetry exfiltration, token budget guardrails are enforced, and proper SpanStatusCode handling is guaranteed.
```typescript
import { createHash } from 'node:crypto';
import { trace, SpanStatusCode } from '@opentelemetry/api';
import { ATTR_GEN_AI_SYSTEM, ATTR_GEN_AI_REQUEST_MODEL, ATTR_GEN_AI_OPERATION_NAME, ATTR_GEN_AI_USAGE_INPUT_TOKENS, ATTR_GEN_AI_USAGE_OUTPUT_TOKENS } from './semanticConventions';

const tracer = trace.getTracer('ai-agent-mesh', '1.0.0');
const MAX_ALLOWED_TOKEN_BUDGET = 8192;

function hashContext(value: string): string {
  return createHash('sha256').update(value).digest('hex');
}

export async function executeAgentStep(
  systemPrompt: string,
  userQuery: string,
  modelName: string,
  llmClient: { complete: (req: { model: string; input: string }) => Promise<{ text: string; inputTokens: number; outputTokens: number }> }
) {
  return tracer.startActiveSpan('chat ' + modelName, async (span) => {
    try {
      span.setAttributes({
        [ATTR_GEN_AI_SYSTEM]: 'anthropic',
        [ATTR_GEN_AI_REQUEST_MODEL]: modelName,
        [ATTR_GEN_AI_OPERATION_NAME]: 'chat',
        'gen_ai.prompt.fingerprint': hashContext(systemPrompt),
        'gen_ai.user_query.fingerprint': hashContext(userQuery)
      });

      const response = await llmClient.complete({
        model: modelName,
        input: `${systemPrompt}\n${userQuery}`
      });

      const totalTokens = response.inputTokens + response.outputTokens;
      span.setAttributes({
        [ATTR_GEN_AI_USAGE_INPUT_TOKENS]: response.inputTokens,
        [ATTR_GEN_AI_USAGE_OUTPUT_TOKENS]: response.outputTokens
      });

      if (totalTokens > MAX_ALLOWED_TOKEN_BUDGET) {
        span.setStatus({
          code: SpanStatusCode.ERROR,
          message: `Token budget breached: ${totalTokens} > ${MAX_ALLOWED_TOKEN_BUDGET}`
        });
      } else {
        span.setStatus({ code: SpanStatusCode.OK });
      }

      return response;
    } catch (error) {
      span.recordException(error instanceof Error ? error : new Error(String(error)));
      span.setStatus({ code: SpanStatusCode.ERROR, message: error instanceof Error ? error.message : 'Unknown inference error' });
      throw error;
    } finally {
      span.end();
    }
  });
}
```

Recommended Agent Skills (askills.dev)

Ready-to-use executable skill functions tailored to this stack.

Architectural Specification & Invariant Rationale

Architectural Invariant Design: OpenTelemetry GenAI Semantic Conventions and Context Leak Guardrail

OpenTelemetry GenAI Semantic Conventions and Context Leak Guardrail defines an industrial-grade behavioral standard for devops engineering. Enforces strict OpenTelemetry GenAI semantic conventions across agentic LLM workflows while preventing PII and confidential context exfiltration through telemetry span attributes. Requires token budget accounting, cryptographic payload hashing over raw prompt injection, and normalized metric dimensions across distributed inference meshes. 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: Raw Prompt Exfiltration and Unstandardized Telemetry in GenAI Traces 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 DriftRaw Prompt Exfiltration and Unstandardized Telemetry in GenAI TracesCritical
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 populate standard OpenTelemetry GenAI attributes (`gen_ai.system`, `gen_ai.request.model`, `gen_ai.operation.name`, `gen_ai.usage.input_tokens`, `gen_ai.usage.output_tokens`).

Engineers MUST ALWAYS populate standard OpenTelemetry GenAI attributes (`gen_ai.system`, `gen_ai.request.model`, `gen_ai.operation.name`, `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.
2

Engineers MUST NOT serialize raw prompt strings, system context, or raw completion payloads into span attributes (`gen_ai.prompt`, `gen_ai.completion`) unless explicit cryptographic differential privacy or PII-redacted scrubbing pipelines are invoked and configured.

Engineers MUST NOT serialize raw prompt strings, system context, or raw completion payloads into span attributes (`gen_ai.prompt`, `gen_ai.completion`) unless explicit cryptographic differential privacy or PII-redacted scrubbing pipelines are invoked and configured.

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 generate a deterministic SHA-256 fingerprint (`gen_ai.prompt.fingerprint`) of prompt templates and system directives to allow trace grouping without exfiltrating confidential tenant data.

Code SHOULD generate a deterministic SHA-256 fingerprint (`gen_ai.prompt.fingerprint`) of prompt templates and system directives to allow trace grouping without exfiltrating confidential tenant data.

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 record token usage counters and track token budget ceiling violations by setting span status to `StatusCode.ERROR` when inference limits or context token budgets are exceeded.

Services MUST record token usage counters and track token budget ceiling violations by setting span status to `StatusCode.ERROR` when inference limits or context token budgets are exceeded.

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 capture sensitive tool execution outputs (such as credentials, API keys, or raw SQL results) inside agent telemetry attributes

Components NEVER capture sensitive tool execution outputs (such as credentials, API keys, or raw SQL results) inside agent telemetry attributes; payload metadata must be limited to sanitised schema descriptions and execution status.

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 GenAI Semantic Conventions and Context Leak Guardrail critical for AI coding assistants?

Enforces strict OpenTelemetry GenAI semantic conventions across agentic LLM workflows while preventing PII and confidential context exfiltration through telemetry span attributes. Requires token budget accounting, cryptographic payload hashing over raw prompt injection, and normalized metric dimensions across distributed inference meshes. 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 (Raw Prompt Exfiltration and Unstandardized Telemetry in GenAI Traces) 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