This specification is maintained by the AgentRules Working Group. Have enhancements or want to claim maintainership?Submit Specification →
devopscritical PriorityID: opentelemetry-genai-token-budget-span-invariants

OpenTelemetry GenAI Semantic Conventions and Token Budget Span Invariants

Enforces strict OpenTelemetry GenAI semantic conventions across autonomous agent loops by propagating token consumption budgets through distributed trace baggage and spans. Every agent reasoning step must validate and deduct from a deterministic token allocation budget, halting execution cascades immediately upon budget breach.

Prohibited Anti-Pattern: Unbounded Agentic Feedback Loops Without Distributed Token Budget Propagation and GenAI Spans

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: OpenTelemetry GenAI Semantic Conventions and Token Budget Span Invariants - Enforces strict OpenTelemetry GenAI semantic conventions across autonomous agent loops by propagating token consumption budgets through distributed trace baggage and spans. Every agent reasoning step must validate and deduct from a deterministic token allocation budget, halting execution cascades immediately upon budget breach.
globs: src/agents/**/*.{ts,tsx}, src/llm/**/*.{ts,tsx}, src/telemetry/**/*.{ts,tsx}, src/orchestration/**/*.{ts,tsx}
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/opentelemetry-genai-token-budget-span-invariants"
---

# OpenTelemetry GenAI Semantic Conventions and Token Budget Span Invariants

> **Severity**: CRITICAL | **Category**: devops
> **Anti-Pattern Warning**: Unbounded Agentic Feedback Loops Without Distributed Token Budget Propagation and GenAI Spans

## System Constraints
You are a Principal Software Architect enforcing OpenTelemetry GenAI Semantic Conventions and deterministic token budget invariants. Mandate that every AI agent step, tool call, and model invocation creates an instrumented span using canonical OpenTelemetry GenAI semantic conventions (v1.28.0+). Every distributed trace context must propagate the total token budget and decrement the remaining budget using trace Baggage or Span Context attributes. When the remaining token budget is exceeded or steps exceed maximum loop depth, the runtime MUST short-circuit the agent cascade deterministically and record the span error status.

## Strict Guidelines
- Engineers MUST ALWAYS wrap every LLM generation and tool execution in an OpenTelemetry span using canonical GenAI attributes ('gen_ai.system', 'gen_ai.request.model', 'gen_ai.usage.input_tokens', 'gen_ai.usage.output_tokens').
- Engineers MUST NOT allow autonomous agent loops to execute without an explicit, monotonically decreasing token budget carried through distributed Context and Baggage.
- Code SHOULD short-circuit agent iteration immediately before invoking model endpoints if the remaining token budget ('gen_ai.budget.tokens_remaining') is less than or equal to zero.
- Services MUST record step indexes using 'gen_ai.agent.step' and emit error span events when cascades are terminated due to token budget depletion.
- Components NEVER execute uninstrumented tool calls or raw LLM client invocations outside of an active trace span context.

## Bad vs Good Implementations
### Autonomous Agent Step Execution with Token Budget Span Invariant

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: The loop has no distributed OpenTelemetry tracing, omits canonical GenAI semantic conventions, and lacks token budget tracking. A recursive hallucination or tool loop will burn quota and compute without observability or hard stop limits.
```typescript
import OpenAI from 'openai';

const openai = new OpenAI();

export async function executeAgentTask(taskPrompt: string) {
  let currentPrompt = taskPrompt;
  let iteration = 0;
  
  // ANTI-PATTERN: Infinite loop vulnerability without trace propagation or budget checks
  while (iteration < 50) {
    const response = await openai.chat.completions.create({
      model: 'gpt-4o',
      messages: [{ role: 'user', content: currentPrompt }]
    });
    
    const reply = response.choices[0]?.message?.content ?? '';
    if (reply.includes('COMPLETE')) return reply;
    
    // Tool cascade without OpenTelemetry spans or token limit verification
    currentPrompt = `Continue processing: ${reply}`;
    iteration++;
  }
  return null;
}
```

#### Production Standard (Correct)
> **Standard**: Adheres strictly to OpenTelemetry GenAI semantic conventions ('gen_ai.system', 'gen_ai.request.model', 'gen_ai.usage.*'). Injects remaining token capacity into Baggage and Span attributes on each step, enforcing an invariant that aborts runaway agent cascades prior to further LLM consumption.
```typescript
import { trace, context, propagation, SpanStatusCode } from '@opentelemetry/api';
import OpenAI from 'openai';

const tracer = trace.getTracer('agent-orchestrator', '1.0.0');
const openai = new OpenAI();

export class TokenBudgetExceededError extends Error {
  constructor(remaining: number) {
    super(`Token budget exceeded: ${remaining} tokens remaining.`);
    this.name = 'TokenBudgetExceededError';
  }
}

export async function executeAgentTask(
  taskPrompt: string,
  initialBudget: number = 8192
): Promise<string> {
  return tracer.startActiveSpan('agent.task.execute', async (parentSpan) => {
    let remainingTokens = initialBudget;
    let currentPrompt = taskPrompt;
    let step = 0;
    const maxSteps = 10;

    try {
      while (step < maxSteps) {
        if (remainingTokens <= 0) {
          throw new TokenBudgetExceededError(remainingTokens);
        }

        const baggage = propagation.createBaggage({
          'token.budget.remaining': { value: remainingTokens.toString() }
        });
        const stepContext = propagation.setBaggage(context.active(), baggage);

        const result = await context.with(stepContext, async () => {
          return tracer.startActiveSpan('gen_ai.client.chat', { attributes: {
            'gen_ai.system': 'openai',
            'gen_ai.request.model': 'gpt-4o',
            'gen_ai.agent.step': step,
            'gen_ai.budget.tokens_remaining': remainingTokens
          }}, async (span) => {
            try {
              const completion = await openai.chat.completions.create({
                model: 'gpt-4o',
                messages: [{ role: 'user', content: currentPrompt }]
              });

              const inputTokens = completion.usage?.prompt_tokens ?? 0;
              const outputTokens = completion.usage?.completion_tokens ?? 0;
              const totalUsed = inputTokens + outputTokens;

              remainingTokens -= totalUsed;

              span.setAttributes({
                'gen_ai.usage.input_tokens': inputTokens,
                'gen_ai.usage.output_tokens': outputTokens,
                'gen_ai.response.finish_reasons': [completion.choices[0]?.finish_reason ?? 'unknown'],
                'gen_ai.budget.tokens_remaining': remainingTokens
              });
              span.setStatus({ code: SpanStatusCode.OK });
              return completion.choices[0]?.message?.content ?? '';
            } catch (err) {
              span.recordException(err as Error);
              span.setStatus({ code: SpanStatusCode.ERROR, message: (err as Error).message });
              throw err;
            } finally {
              span.end();
            }
          });
        });

        if (result.includes('COMPLETE')) return result;
        currentPrompt = `Continue processing: ${result}`;
        step++;
      }
      return 'MAX_STEPS_REACHED';
    } catch (error) {
      parentSpan.recordException(error as Error);
      parentSpan.setStatus({ code: SpanStatusCode.ERROR, message: (error as Error).message });
      throw error;
    } finally {
      parentSpan.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 Token Budget Span Invariants

OpenTelemetry GenAI Semantic Conventions and Token Budget Span Invariants defines an industrial-grade behavioral standard for devops engineering. Enforces strict OpenTelemetry GenAI semantic conventions across autonomous agent loops by propagating token consumption budgets through distributed trace baggage and spans. Every agent reasoning step must validate and deduct from a deterministic token allocation budget, halting execution cascades immediately upon budget breach. 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: Unbounded Agentic Feedback Loops Without Distributed Token Budget Propagation and GenAI Spans 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 DriftUnbounded Agentic Feedback Loops Without Distributed Token Budget Propagation and GenAI SpansCritical
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 wrap every LLM generation and tool execution in an OpenTelemetry span using canonical GenAI attributes ('gen_ai.system', 'gen_ai.request.model', 'gen_ai.usage.input_tokens', 'gen_ai.usage.output_tokens').

Engineers MUST ALWAYS wrap every LLM generation and tool execution in an OpenTelemetry span using canonical GenAI attributes ('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.
2

Engineers MUST NOT allow autonomous agent loops to execute without an explicit, monotonically decreasing token budget carried through distributed Context and Baggage.

Engineers MUST NOT allow autonomous agent loops to execute without an explicit, monotonically decreasing token budget carried through distributed Context and Baggage.

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 short-circuit agent iteration immediately before invoking model endpoints if the remaining token budget ('gen_ai.budget.tokens_remaining') is less than or equal to zero.

Code SHOULD short-circuit agent iteration immediately before invoking model endpoints if the remaining token budget ('gen_ai.budget.tokens_remaining') is less than or equal to zero.

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 step indexes using 'gen_ai.agent.step' and emit error span events when cascades are terminated due to token budget depletion.

Services MUST record step indexes using 'gen_ai.agent.step' and emit error span events when cascades are terminated due to token budget depletion.

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 execute uninstrumented tool calls or raw LLM client invocations outside of an active trace span context.

Components NEVER execute uninstrumented tool calls or raw LLM client invocations outside of an active trace span context.

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 Token Budget Span Invariants critical for AI coding assistants?

Enforces strict OpenTelemetry GenAI semantic conventions across autonomous agent loops by propagating token consumption budgets through distributed trace baggage and spans. Every agent reasoning step must validate and deduct from a deterministic token allocation budget, halting execution cascades immediately upon budget breach. 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 (Unbounded Agentic Feedback Loops Without Distributed Token Budget Propagation and GenAI Spans) 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