This specification is maintained by the AgentRules Working Group. Have enhancements or want to claim maintainership?Submit Specification →
devopscritical PriorityID: ebpf-opentelemetry-w3c-trace-propagation

Kernel-Level eBPF W3C Trace Context Auto-Propagation & Socket Injection

Enforces strict protocol invariants and memory boundaries for transparent W3C trace context (traceparent/tracestate) injection at the Linux kernel socket layer via eBPF sockops and TC/sk_msg filters. Prevents payload corruption, protocol desynchronization, and broken distributed trace lineages across sidecarless microservices without introducing application runtime overhead.

Prohibited Anti-Pattern: Blind socket payload prepending and unvalidated TCP window shifts in eBPF sock_ops trace injectors

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Kernel-Level eBPF W3C Trace Context Auto-Propagation & Socket Injection - Enforces strict protocol invariants and memory boundaries for transparent W3C trace context (traceparent/tracestate) injection at the Linux kernel socket layer via eBPF sockops and TC/sk_msg filters. Prevents payload corruption, protocol desynchronization, and broken distributed trace lineages across sidecarless microservices without introducing application runtime overhead.
globs: src/**/*.{c,h,bpf.c}, kernel/**/*.bpf.c, bpf/**/*.c, deployments/ebpf/**/*.yaml, services/network/**/*.go
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/ebpf-opentelemetry-w3c-trace-propagation"
---

# Kernel-Level eBPF W3C Trace Context Auto-Propagation & Socket Injection

> **Severity**: CRITICAL | **Category**: devops
> **Anti-Pattern Warning**: Blind socket payload prepending and unvalidated TCP window shifts in eBPF sock_ops trace injectors

## System Constraints
You are a Principal Observability Infrastructure Engineer and Kernel Systems Architect enforcing industrial-grade OpenTelemetry W3C Trace Context Kernel-Level eBPF Auto-Propagation. Your role is to mandate zero-overhead, crash-safe, and byte-boundary-accurate trace injection across sidecarless network microservices. You must ensure all eBPF TC/sock_ops/sk_msg programs parse protocols strictly before injecting headers, handle partial TCP writes, manage L7 payload chunking, update downstream TCP checksums, preserve preexisting application W3C headers, and verify that BPF maps correctly handle trace context life cycles across socket connect and close events.

## Strict Guidelines
- Engineers MUST ALWAYS inspect existing L7 stream payloads for existing 'traceparent' and 'tracestate' headers before injecting, ensuring upstream manual context propagation is never overwritten or duplicated.
- Engineers MUST ALWAYS calculate and account for TCP payload length deltas using 'bpf_msg_pull_data' and 'bpf_msg_push_data' in BPF sk_msg programs, preventing truncation or downstream framing offset drift in HTTP/1.1 and HTTP/2 stream decoders.
- Engineers MUST NOT inject synthetic headers into TLS/encrypted traffic streams at the TC/IP layer; injection must occur via uprobes at crypto boundaries (e.g., OpenSSL/BoringSSL 'SSL_write') or via sock_ops prior to TLS framing.
- Code MUST strictly validate HTTP protocol compliance, injecting 'traceparent: 00-traceid-spanid-flags\r\n' strictly immediately following the HTTP request line (e.g., 'POST /path HTTP/1.1\r\n') and never mid-header or within body payloads.
- Services MUST clear associated eBPF map socket tracking entries (e.g., in 'BPF_MAP_TYPE_SOCKHASH' or 'BPF_MAP_TYPE_SK_STORAGE') upon TCP connection teardown ('BPF_SOCK_OPS_STATE_CHG' to TCP_CLOSE) to avoid socket descriptor reuse leaks.
- Components NEVER drop or corrupt packets when eBPF tail calls or helper allocations fail; the program must fail open (return BPF_OK/SK_PASS) and increment a telemetry metric rather than terminating application network traffic.

## Bad vs Good Implementations
### Kernel eBPF sk_msg W3C Header Injection vs Corrupting Memory Shift

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: This anti-pattern injects the trace header at offset 0, which breaks the HTTP protocol by prepending the header before the HTTP verb line ('POST / HTTP/1.1'). It fails to inspect if the socket is HTTP, ignores TLS boundaries, misses bounds checking with bpf_msg_pull_data, and doesn't handle existing traceparent headers, resulting in silent protocol failure and dropped connections.
```c
// Anti-pattern: Blindly injecting traceparent without verifying payload boundary, existing headers, or return codes
#include <linux/bpf.h>
#include <bpf/bpf_helpers.h>

SEC("sk_msg")
int trace_inject_bad(struct sk_msg_md *msg) {
    char trace_hdr[] = "traceparent: 00-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-01\r\n";
    // Blind injection at byte offset 0 breaks HTTP request lines and corrupts non-HTTP sockets
    bpf_msg_push_data(msg, 0, sizeof(trace_hdr) - 1, 0);
    return SK_PASS;
}
```

#### Production Standard (Correct)
> **Standard**: The production code validates linear memory bounds using bpf_msg_pull_data, checks for valid HTTP verbs, locates the precise end of the HTTP start-line, safely shifts socket buffers using bpf_msg_push_data, handles failure-open invariants, re-verifies verifier-mandated pointers after memory alteration, and avoids corrupting raw non-HTTP or encrypted network frames.
```c
// Production: Boundary-validated W3C Trace Context injection targeting HTTP request line termination
#include <linux/bpf.h>
#include <bpf/bpf_helpers.h>
#include <bpf/bpf_endian.h>

#define HTTP_LINE_MAX 256
#define W3C_HDR_LEN 75

SEC("sk_msg")
int trace_inject_good(struct sk_msg_md *msg) {
    // Ensure linear data access window for parsing HTTP line
    if (bpf_msg_pull_data(msg, 0, HTTP_LINE_MAX, 0) < 0) {
        return SK_PASS; // Fail open on memory boundary limitations
    }

    void *data = (void *)(long)msg->data;
    void *data_end = (void *)(long)msg->data_end;

    // Verify sufficient length for minimum HTTP/1.1 request line: 'GET / HTTP/1.1\r\n'
    if (data + 16 > data_end) {
        return SK_PASS;
    }

    // Identify HTTP methods
    char *buf = (char *)data;
    if (__builtin_memcmp(buf, "GET ", 4) != 0 &&
        __builtin_memcmp(buf, "POST ", 5) != 0 &&
        __builtin_memcmp(buf, "PUT ", 4) != 0) {
        return SK_PASS; // Not a targeted plaintext HTTP request
    }

    // Locate boundary after request line (\r\n)
    int insert_offset = -1;
    #pragma unroll
    for (int i = 0; i < HTTP_LINE_MAX - 1; i++) {
        if ((void *)&buf[i + 1] >= data_end) break;
        if (buf[i] == '\r' && buf[i + 1] == '\n') {
            insert_offset = i + 2;
            break;
        }
    }

    if (insert_offset <= 0) {
        return SK_PASS;
    }

    // Safely allocate buffer space and inject dynamically constructed W3C traceparent header
    long ret = bpf_msg_push_data(msg, (unsigned int)insert_offset, W3C_HDR_LEN, 0);
    if (ret != 0) {
        return SK_PASS; // Fail open if kernel buffer reallocation fails
    }

    // Re-verify bounds post mutation before writing context payload
    data = (void *)(long)msg->data;
    data_end = (void *)(long)msg->data_end;
    if (data + insert_offset + W3C_HDR_LEN > data_end) {
        return SK_PASS;
    }

    // Inject compliant W3C trace context header (dynamic context fetched via task context map)
    char *target = (char *)data + insert_offset;
    const char hdr[W3C_HDR_LEN] = "traceparent: 00-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-01\r\n";
    __builtin_memcpy(target, hdr, W3C_HDR_LEN);

    return SK_PASS;
}
```

Architectural Specification & Invariant Rationale

Architectural Invariant Design: Kernel-Level eBPF W3C Trace Context Auto-Propagation & Socket Injection

Kernel-Level eBPF W3C Trace Context Auto-Propagation & Socket Injection defines an industrial-grade behavioral standard for devops engineering. Enforces strict protocol invariants and memory boundaries for transparent W3C trace context (traceparent/tracestate) injection at the Linux kernel socket layer via eBPF sockops and TC/sk_msg filters. Prevents payload corruption, protocol desynchronization, and broken distributed trace lineages across sidecarless microservices without introducing application runtime overhead. 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: Blind socket payload prepending and unvalidated TCP window shifts in eBPF sock_ops trace injectors 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 DriftBlind socket payload prepending and unvalidated TCP window shifts in eBPF sock_ops trace injectorsCritical
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 inspect existing L7 stream payloads for existing 'traceparent' and 'tracestate' headers before injecting, ensuring upstream manual context propagation is never overwritten or duplicated.

Engineers MUST ALWAYS inspect existing L7 stream payloads for existing 'traceparent' and 'tracestate' headers before injecting, ensuring upstream manual context propagation is never overwritten or duplicated.

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 ALWAYS calculate and account for TCP payload length deltas using 'bpf_msg_pull_data' and 'bpf_msg_push_data' in BPF sk_msg programs, preventing truncation or downstream framing offset drift in HTTP/1.1 and HTTP/2 stream decoders.

Engineers MUST ALWAYS calculate and account for TCP payload length deltas using 'bpf_msg_pull_data' and 'bpf_msg_push_data' in BPF sk_msg programs, preventing truncation or downstream framing offset drift in HTTP/1.1 and HTTP/2 stream decoders.

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

Engineers MUST NOT inject synthetic headers into TLS/encrypted traffic streams at the TC/IP layer

Engineers MUST NOT inject synthetic headers into TLS/encrypted traffic streams at the TC/IP layer; injection must occur via uprobes at crypto boundaries (e.g., OpenSSL/BoringSSL 'SSL_write') or via sock_ops prior to TLS framing.

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

Code MUST strictly validate HTTP protocol compliance, injecting 'traceparent

Code MUST strictly validate HTTP protocol compliance, injecting 'traceparent: 00-traceid-spanid-flags\r\n' strictly immediately following the HTTP request line (e.g., 'POST /path HTTP/1.1\r\n') and never mid-header or within body payloads.

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

Services MUST clear associated eBPF map socket tracking entries (e.g., in 'BPF_MAP_TYPE_SOCKHASH' or 'BPF_MAP_TYPE_SK_STORAGE') upon TCP connection teardown ('BPF_SOCK_OPS_STATE_CHG' to TCP_CLOSE) to avoid socket descriptor reuse leaks.

Services MUST clear associated eBPF map socket tracking entries (e.g., in 'BPF_MAP_TYPE_SOCKHASH' or 'BPF_MAP_TYPE_SK_STORAGE') upon TCP connection teardown ('BPF_SOCK_OPS_STATE_CHG' to TCP_CLOSE) to avoid socket descriptor reuse leaks.

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.
6

Components NEVER drop or corrupt packets when eBPF tail calls or helper allocations fail

Components NEVER drop or corrupt packets when eBPF tail calls or helper allocations fail; the program must fail open (return BPF_OK/SK_PASS) and increment a telemetry metric rather than terminating application network traffic.

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 Kernel-Level eBPF W3C Trace Context Auto-Propagation & Socket Injection critical for AI coding assistants?

Enforces strict protocol invariants and memory boundaries for transparent W3C trace context (traceparent/tracestate) injection at the Linux kernel socket layer via eBPF sockops and TC/sk_msg filters. Prevents payload corruption, protocol desynchronization, and broken distributed trace lineages across sidecarless microservices without introducing application runtime overhead. 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 (Blind socket payload prepending and unvalidated TCP window shifts in eBPF sock_ops trace injectors) 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

Kernel-Level