Skip to content

The platform for continuously improving AI agents.

27.1 KB
Raw Blame
"""Locust load & concurrency benchmark for the deployed Overmind Rust OTel server.

Usage:
  # Pure trace ingestion benchmark (100% POST /v1/traces, 3 spans/req):
  locust -f collector/scripts/locustfile.py --host http://127.0.0.1:4318 \
      --headless -u 50 -r 25 -t 30s IngestOnlyUser

  # Mixed UI + ingest benchmark (3 spans/req):
  locust -f collector/scripts/locustfile.py --host http://127.0.0.1:4318 \
      --headless -u 50 -r 25 -t 30s MixedWorkloadUser

  # High-load multi-process ingest (default 10 spans/req, optional LOCUST_GZIP=1):
  LOCUST_SPANS_PER_REQ=10 locust -f collector/scripts/locustfile.py --host http://127.0.0.1:4318 \
      --headless --processes 4 -u 400 -r 100 -t 30s HighLoadIngestUser

  # High-load multi-process mixed ingest + analytics RPCs:
  LOCUST_SPANS_PER_REQ=10 locust -f collector/scripts/locustfile.py --host http://127.0.0.1:4318 \
      --headless --processes 4 -u 400 -r 100 -t 30s HighLoadMixedUser

  # Pure OTLP traces ceiling (1 realistic 3-span trace/req, gzip on by default):
  locust -f collector/scripts/locustfile.py --host http://127.0.0.1:4318 \
      --headless --processes 4 -u 100 -r 50 -t 25s PureTracesIngestUser

  # Combined OTLP ingest ceiling (traces + metrics + logs, gzip on by default):
  locust -f collector/scripts/locustfile.py --host http://127.0.0.1:4318 \
      --headless --processes 4 -u 100 -r 50 -t 25s AllOtlpIngestUser
"""

import gzip
import json
import os
import random
import time

from locust import FastHttpUser, between, constant, events, task
from locust.runners import WorkerRunner

SERVICES = ["support-copilot", "billing-agent", "research-agent", "triage-bot"]
MODELS = ["openai/gpt-5-mini", "anthropic/claude-sonnet-4.5"]
TOOLS = ["search_kb", "lookup_order", "check_refund_policy", "query_crm"]
QUESTIONS = [
    "Where is my order #48291?",
    "Can I get a refund on my annual subscription?",
    "How do I rotate my workspace API key?",
    "Why did my invoice double this month?",
]
ANSWERS = [
    "Order #48291 shipped via DHL and arrives tomorrow by 5 PM.",
    "Annual plans are eligible for a full refund within 14 days; I have started the request.",
    "Open Settings -> API Keys and click Rotate to issue a new token immediately.",
    "Your invoice reflects the 3 additional seats added on the 12th.",
]

JSON_HEADERS = {"content-type": "application/json"}
GZIP_JSON_HEADERS = {"content-type": "application/json", "content-encoding": "gzip"}

LOCUST_SPANS_PER_REQ = max(1, int(os.environ.get("LOCUST_SPANS_PER_REQ", "10")))
LOCUST_GZIP = os.environ.get("LOCUST_GZIP", "0").strip().lower() in ("1", "true", "yes")
OTLP_INGEST_GZIP = os.environ.get("LOCUST_GZIP", "1").strip().lower() in ("1", "true", "yes")


def _kv_str(key: str, value: str) -> dict:
    return {"key": key, "value": {"stringValue": value}}


def _kv_int(key: str, value: int) -> dict:
    return {"key": key, "value": {"intValue": str(value)}}


def _kv_float(key: str, value: float) -> dict:
    return {"key": key, "value": {"doubleValue": value}}


def make_trace_payload() -> dict:
    """Builds a realistic 3-span agent trace (agent -> llm -> tool) in OTLP JSON."""
    now = time.time_ns()
    trace_id = os.urandom(16).hex()
    root_id = os.urandom(8).hex()
    llm_id = os.urandom(8).hex()
    tool_id = os.urandom(8).hex()

    service = random.choice(SERVICES)
    model = random.choice(MODELS)
    tool = random.choice(TOOLS)
    idx = random.randrange(len(QUESTIONS))
    in_tokens = random.randint(120, 600)
    out_tokens = random.randint(30, 180)
    cost = round((in_tokens * 0.00000025) + (out_tokens * 0.000002), 6)
    is_err = random.random() < 0.02

    return {
        "resourceSpans": [
            {
                "resource": {
                    "attributes": [
                        _kv_str("service.name", service),
                        _kv_str("deployment.environment.name", "production"),
                    ]
                },
                "scopeSpans": [
                    {
                        "scope": {"name": "overmind.agent", "version": "1.0.0"},
                        "spans": [
                            {
                                "traceId": trace_id,
                                "spanId": root_id,
                                "name": "agent.run",
                                "kind": 2,
                                "startTimeUnixNano": str(now),
                                "endTimeUnixNano": str(now + 420_000_000),
                                "status": {
                                    "code": 2 if is_err else 1,
                                    "message": "tool timeout" if is_err else "",
                                },
                                "attributes": [
                                    _kv_str("overmind.span.type", "agent"),
                                    _kv_str("overmind.input", QUESTIONS[idx]),
                                    _kv_str("overmind.output", ANSWERS[idx]),
                                    _kv_str("code.filepath", f"src/agents/{service}.py"),
                                    _kv_str("code.function", "handle_request"),
                                    _kv_str("overmind.output.label", "error" if is_err else "stop"),
                                ],
                            },
                            {
                                "traceId": trace_id,
                                "spanId": llm_id,
                                "parentSpanId": root_id,
                                "name": "llm.chat",
                                "kind": 3,
                                "startTimeUnixNano": str(now + 20_000_000),
                                "endTimeUnixNano": str(now + 250_000_000),
                                "status": {"code": 1},
                                "attributes": [
                                    _kv_str("gen_ai.operation.name", "chat"),
                                    _kv_str("gen_ai.request.model", model),
                                    _kv_int("gen_ai.usage.input_tokens", in_tokens),
                                    _kv_int("gen_ai.usage.output_tokens", out_tokens),
                                    _kv_int("gen_ai.usage.total_tokens", in_tokens + out_tokens),
                                    _kv_float("overmind.cost", cost),
                                    _kv_str("overmind.input", QUESTIONS[idx]),
                                    _kv_str("overmind.output", ANSWERS[idx]),
                                ],
                            },
                            {
                                "traceId": trace_id,
                                "spanId": tool_id,
                                "parentSpanId": root_id,
                                "name": "execute_tool",
                                "kind": 1,
                                "startTimeUnixNano": str(now + 260_000_000),
                                "endTimeUnixNano": str(now + 390_000_000),
                                "status": {
                                    "code": 2 if is_err else 1,
                                    "message": "504 backend timeout" if is_err else "",
                                },
                                "attributes": [
                                    _kv_str("gen_ai.tool.name", tool),
                                    _kv_str("code.filepath", f"src/tools/{tool}.py"),
                                    _kv_str("code.function", tool),
                                ],
                            },
                        ],
                    }
                ],
            }
        ]
    }


def make_batched_trace_payload(spans_per_req: int = LOCUST_SPANS_PER_REQ) -> dict:
    """Builds a realistic N-span agent trace (1 root agent + alternating LLM & tool spans)."""
    now = time.time_ns()
    trace_id = os.urandom(16).hex()
    root_id = os.urandom(8).hex()

    service = random.choice(SERVICES)
    idx = random.randrange(len(QUESTIONS))
    is_err = random.random() < 0.02

    child_count = max(0, spans_per_req - 1)
    total_duration_ns = max(420_000_000, (child_count + 1) * 140_000_000)

    spans = [
        {
            "traceId": trace_id,
            "spanId": root_id,
            "name": "agent.run",
            "kind": 2,
            "startTimeUnixNano": str(now),
            "endTimeUnixNano": str(now + total_duration_ns),
            "status": {
                "code": 2 if is_err else 1,
                "message": "tool timeout" if is_err else "",
            },
            "attributes": [
                _kv_str("overmind.span.type", "agent"),
                _kv_str("overmind.input", QUESTIONS[idx]),
                _kv_str("overmind.output", ANSWERS[idx]),
                _kv_str("code.filepath", f"src/agents/{service}.py"),
                _kv_str("code.function", "handle_request"),
                _kv_str("overmind.output.label", "error" if is_err else "stop"),
            ],
        }
    ]

    for step in range(child_count):
        span_id = os.urandom(8).hex()
        start_ns = now + (step + 1) * 120_000_000
        if step % 2 == 0:
            model = random.choice(MODELS)
            in_tokens = random.randint(120, 600)
            out_tokens = random.randint(30, 180)
            cost = round((in_tokens * 0.00000025) + (out_tokens * 0.000002), 6)
            spans.append(
                {
                    "traceId": trace_id,
                    "spanId": span_id,
                    "parentSpanId": root_id,
                    "name": "llm.chat",
                    "kind": 3,
                    "startTimeUnixNano": str(start_ns),
                    "endTimeUnixNano": str(start_ns + 110_000_000),
                    "status": {"code": 1},
                    "attributes": [
                        _kv_str("gen_ai.operation.name", "chat"),
                        _kv_str("gen_ai.request.model", model),
                        _kv_int("gen_ai.usage.input_tokens", in_tokens),
                        _kv_int("gen_ai.usage.output_tokens", out_tokens),
                        _kv_int("gen_ai.usage.total_tokens", in_tokens + out_tokens),
                        _kv_float("overmind.cost", cost),
                        _kv_str("overmind.input", QUESTIONS[idx]),
                        _kv_str("overmind.output", ANSWERS[idx]),
                    ],
                }
            )
        else:
            tool = random.choice(TOOLS)
            step_err = is_err and step == child_count - 1
            spans.append(
                {
                    "traceId": trace_id,
                    "spanId": span_id,
                    "parentSpanId": root_id,
                    "name": "execute_tool",
                    "kind": 1,
                    "startTimeUnixNano": str(start_ns),
                    "endTimeUnixNano": str(start_ns + 90_000_000),
                    "status": {
                        "code": 2 if step_err else 1,
                        "message": "504 backend timeout" if step_err else "",
                    },
                    "attributes": [
                        _kv_str("gen_ai.tool.name", tool),
                        _kv_str("code.filepath", f"src/tools/{tool}.py"),
                        _kv_str("code.function", tool),
                    ],
                }
            )

    return {
        "resourceSpans": [
            {
                "resource": {
                    "attributes": [
                        _kv_str("service.name", service),
                        _kv_str("deployment.environment.name", "production"),
                    ]
                },
                "scopeSpans": [
                    {
                        "scope": {"name": "overmind.agent", "version": "1.0.0"},
                        "spans": spans,
                    }
                ],
            }
        ]
    }


def make_metrics_payload() -> dict:
    """Builds a realistic OTLP ExportMetricsServiceRequest with 3 gauge/sum data points."""
    now = str(time.time_ns())
    service = random.choice(SERVICES)
    model = random.choice(MODELS)
    latency_ms = round(random.uniform(120.0, 680.0), 2)
    total_tokens = random.randint(150, 780)
    is_err = random.random() < 0.02

    return {
        "resourceMetrics": [
            {
                "resource": {
                    "attributes": [
                        _kv_str("service.name", service),
                        _kv_str("deployment.environment.name", "production"),
                    ]
                },
                "scopeMetrics": [
                    {
                        "scope": {"name": "overmind.agent", "version": "1.0.0"},
                        "metrics": [
                            {
                                "name": "agent.llm.latency",
                                "unit": "ms",
                                "gauge": {
                                    "dataPoints": [
                                        {
                                            "timeUnixNano": now,
                                            "asDouble": latency_ms,
                                            "attributes": [
                                                _kv_str("gen_ai.request.model", model),
                                                _kv_str("gen_ai.operation.name", "chat"),
                                            ],
                                        }
                                    ]
                                },
                            },
                            {
                                "name": "agent.tokens.total",
                                "unit": "1",
                                "sum": {
                                    "aggregationTemporality": 2,
                                    "isMonotonic": True,
                                    "dataPoints": [
                                        {
                                            "timeUnixNano": now,
                                            "asInt": str(total_tokens),
                                            "attributes": [
                                                _kv_str("gen_ai.request.model", model),
                                            ],
                                        }
                                    ],
                                },
                            },
                            {
                                "name": "agent.runs",
                                "unit": "1",
                                "sum": {
                                    "aggregationTemporality": 2,
                                    "isMonotonic": True,
                                    "dataPoints": [
                                        {
                                            "timeUnixNano": now,
                                            "asInt": "1",
                                            "attributes": [
                                                _kv_str(
                                                    "overmind.output.label",
                                                    "error" if is_err else "stop",
                                                ),
                                            ],
                                        }
                                    ],
                                },
                            },
                        ],
                    }
                ],
            }
        ]
    }


def make_logs_payload() -> dict:
    """Builds a realistic OTLP ExportLogsServiceRequest with 3 structured log records."""
    now = time.time_ns()
    trace_id = os.urandom(16).hex()
    root_id = os.urandom(8).hex()
    llm_id = os.urandom(8).hex()
    tool_id = os.urandom(8).hex()

    service = random.choice(SERVICES)
    model = random.choice(MODELS)
    tool = random.choice(TOOLS)
    total_tokens = random.randint(150, 780)
    is_err = random.random() < 0.02

    return {
        "resourceLogs": [
            {
                "resource": {
                    "attributes": [
                        _kv_str("service.name", service),
                        _kv_str("deployment.environment.name", "production"),
                    ]
                },
                "scopeLogs": [
                    {
                        "scope": {"name": "overmind.agent", "version": "1.0.0"},
                        "logRecords": [
                            {
                                "timeUnixNano": str(now),
                                "observedTimeUnixNano": str(now + 1_000_000),
                                "severityNumber": 9,
                                "severityText": "INFO",
                                "body": {"stringValue": "started agent run"},
                                "traceId": trace_id,
                                "spanId": root_id,
                                "attributes": [
                                    _kv_str("overmind.span.type", "agent"),
                                    _kv_str("code.function", "handle_request"),
                                ],
                            },
                            {
                                "timeUnixNano": str(now + 200_000_000),
                                "observedTimeUnixNano": str(now + 201_000_000),
                                "severityNumber": 9,
                                "severityText": "INFO",
                                "body": {
                                    "stringValue": f"llm completion returned ({total_tokens} tokens)"
                                },
                                "traceId": trace_id,
                                "spanId": llm_id,
                                "attributes": [
                                    _kv_str("gen_ai.request.model", model),
                                    _kv_int("gen_ai.usage.total_tokens", total_tokens),
                                ],
                            },
                            {
                                "timeUnixNano": str(now + 390_000_000),
                                "observedTimeUnixNano": str(now + 391_000_000),
                                "severityNumber": 17 if is_err else 9,
                                "severityText": "ERROR" if is_err else "INFO",
                                "body": {
                                    "stringValue": f"tool {tool} timeout"
                                    if is_err
                                    else f"tool {tool} succeeded"
                                },
                                "traceId": trace_id,
                                "spanId": tool_id,
                                "attributes": (
                                    [
                                        _kv_str("gen_ai.tool.name", tool),
                                        _kv_str("error.type", "TimeoutError"),
                                    ]
                                    if is_err
                                    else [_kv_str("gen_ai.tool.name", tool)]
                                ),
                            },
                        ],
                    }
                ],
            }
        ]
    }


def _post_otlp(client, path: str, payload: dict, use_gzip: bool, name: str):
    raw = json.dumps(payload, separators=(",", ":")).encode("utf-8")
    if use_gzip:
        body = gzip.compress(raw, compresslevel=1)
        headers = GZIP_JSON_HEADERS
    else:
        body = raw
        headers = JSON_HEADERS

    with client.post(
        path,
        data=body,
        headers=headers,
        name=name,
        catch_response=True,
    ) as resp:
        if resp.status_code == 200:
            resp.success()
        elif resp.status_code == 503:
            resp.failure("503 backpressure")
        elif resp.status_code == 0:
            err_kind = type(resp.error).__name__ if resp.error else "connection/timeout"
            resp.failure(f"timeout/conn ({err_kind})")
        else:
            resp.failure(f"HTTP {resp.status_code}")


def _post_checked(client, path: str, payload: dict, name: str):
    with client.post(
        path,
        json=payload,
        headers=JSON_HEADERS,
        name=name,
        catch_response=True,
    ) as resp:
        if resp.status_code == 200:
            resp.success()
        elif resp.status_code == 503:
            resp.failure("503 backpressure")
        else:
            resp.failure(f"HTTP {resp.status_code}: {resp.text[:120]}")


def _post_batched_traces(client, spans_per_req: int, use_gzip: bool, name: str = "POST /v1/traces"):
    raw = json.dumps(make_batched_trace_payload(spans_per_req), separators=(",", ":")).encode(
        "utf-8"
    )
    if use_gzip:
        body = gzip.compress(raw, compresslevel=1)
        headers = GZIP_JSON_HEADERS
    else:
        body = raw
        headers = JSON_HEADERS

    with client.post(
        "/v1/traces",
        data=body,
        headers=headers,
        name=name,
        catch_response=True,
    ) as resp:
        if resp.status_code == 200:
            resp.success()
        elif resp.status_code == 503:
            resp.failure("503 backpressure")
        else:
            resp.failure(f"HTTP {resp.status_code}: {resp.text[:120]}")


class IngestOnlyUser(FastHttpUser):
    """100% POST /v1/traces benchmark for measuring raw non-blocking ingest throughput."""

    wait_time = between(0.0, 0.01)

    @task
    def ingest_trace(self):
        _post_checked(self.client, "/v1/traces", make_trace_payload(), "POST /v1/traces")


class MixedWorkloadUser(FastHttpUser):
    """Realistic mixed workload: trace ingestion + UI ConnectRPC queries + /healthz."""

    wait_time = between(0.0, 0.01)

    @task(10)
    def ingest_trace(self):
        _post_checked(self.client, "/v1/traces", make_trace_payload(), "POST /v1/traces")

    @task(2)
    def list_traces(self):
        _post_checked(
            self.client,
            "/otel.trace.v1.TraceService/ListTraces",
            {"pageSize": 25},
            "RPC ListTraces",
        )

    @task(1)
    def get_signal_insights(self):
        _post_checked(
            self.client,
            "/otel.signals.v1.SignalService/GetSignalInsights",
            {},
            "RPC GetSignalInsights",
        )

    @task(1)
    def get_graph(self):
        _post_checked(
            self.client,
            "/otel.graph.v1.GraphService/GetGraph",
            {"limitPaths": 50},
            "RPC GetGraph",
        )

    @task(1)
    def get_telemetry_metrics(self):
        _post_checked(
            self.client,
            "/otel.trace.v1.TraceService/GetTelemetryMetrics",
            {},
            "RPC GetTelemetryMetrics",
        )

    @task(1)
    def healthz(self):
        with self.client.get("/healthz", name="GET /healthz", catch_response=True) as resp:
            if resp.status_code == 200:
                resp.success()
            else:
                resp.failure(f"HTTP {resp.status_code}")


class HighLoadIngestUser(FastHttpUser):
    """Zero-wait high-load batched OTLP ingest user (default 10 spans/req, optional gzip)."""

    wait_time = constant(0)

    @task
    def ingest_batched_trace(self):
        _post_batched_traces(self.client, LOCUST_SPANS_PER_REQ, LOCUST_GZIP, "POST /v1/traces")


class HighLoadMixedUser(FastHttpUser):
    """Zero-wait high-load mix: batched 10-span ingest + concurrent dashboard RPCs + /healthz."""

    wait_time = constant(0)

    @task(10)
    def ingest_batched_trace(self):
        _post_batched_traces(self.client, LOCUST_SPANS_PER_REQ, LOCUST_GZIP, "POST /v1/traces")

    @task(2)
    def list_traces(self):
        _post_checked(
            self.client,
            "/otel.trace.v1.TraceService/ListTraces",
            {"pageSize": 25},
            "RPC ListTraces",
        )

    @task(1)
    def get_telemetry_metrics(self):
        _post_checked(
            self.client,
            "/otel.trace.v1.TraceService/GetTelemetryMetrics",
            {},
            "RPC GetTelemetryMetrics",
        )

    @task(1)
    def get_signal_insights(self):
        _post_checked(
            self.client,
            "/otel.signals.v1.SignalService/GetSignalInsights",
            {},
            "RPC GetSignalInsights",
        )

    @task(1)
    def get_graph(self):
        _post_checked(
            self.client,
            "/otel.graph.v1.GraphService/GetGraph",
            {"limitPaths": 50},
            "RPC GetGraph",
        )

    @task(1)
    def healthz(self):
        with self.client.get("/healthz", name="GET /healthz", catch_response=True) as resp:
            if resp.status_code == 200:
                resp.success()
            else:
                resp.failure(f"HTTP {resp.status_code}")


class PureTracesIngestUser(FastHttpUser):
    """Zero-wait 100% POST /v1/traces ceiling user (1 realistic 3-span trace/req, gzip default on)."""

    wait_time = constant(0)

    @task
    def ingest_trace(self):
        _post_otlp(
            self.client,
            "/v1/traces",
            make_trace_payload(),
            OTLP_INGEST_GZIP,
            "POST /v1/traces",
        )


class AllOtlpIngestUser(FastHttpUser):
    """Zero-wait OTLP-only ingest mix: 60% traces, 20% metrics, 20% logs (gzip default on)."""

    wait_time = constant(0)

    @task(6)
    def ingest_trace(self):
        _post_otlp(
            self.client,
            "/v1/traces",
            make_trace_payload(),
            OTLP_INGEST_GZIP,
            "POST /v1/traces",
        )

    @task(2)
    def ingest_metrics(self):
        _post_otlp(
            self.client,
            "/v1/metrics",
            make_metrics_payload(),
            OTLP_INGEST_GZIP,
            "POST /v1/metrics",
        )

    @task(2)
    def ingest_logs(self):
        _post_otlp(
            self.client,
            "/v1/logs",
            make_logs_payload(),
            OTLP_INGEST_GZIP,
            "POST /v1/logs",
        )


@events.quitting.add_listener
def report_ingest_spans(environment, **_):
    if isinstance(environment.runner, WorkerRunner):
        return

    user_names = {cls.__name__ for cls in (environment.user_classes or [])}
    is_high_load = any(name.startswith("HighLoad") for name in user_names)
    is_otlp_ceiling = bool(user_names & {"PureTracesIngestUser", "AllOtlpIngestUser"})

    spans_per_req = LOCUST_SPANS_PER_REQ if is_high_load else 3
    use_gzip = OTLP_INGEST_GZIP if is_otlp_ceiling else (LOCUST_GZIP if is_high_load else False)

    for path, unit_label, items_per_req in (
        ("POST /v1/traces", "spans", spans_per_req),
        ("POST /v1/metrics", "points", 3),
        ("POST /v1/logs", "records", 3),
    ):
        stats = environment.stats.get(path, "POST")
        if stats and stats.num_requests:
            accepted_ratio = (stats.num_requests - stats.num_failures) / stats.num_requests
            accepted_rps = stats.total_rps * accepted_ratio
            print(
                f"\n[summary] {path}: {stats.total_rps:.1f} req/s "
                f"(accepted={accepted_rps:.1f} req/s, {accepted_rps * items_per_req:.0f} accepted {unit_label}/s "
                f"@ {items_per_req} {unit_label}/req, gzip={use_gzip}, "
                f"p50={stats.get_response_time_percentile(0.50):.0f}ms, "
                f"p95={stats.get_response_time_percentile(0.95):.0f}ms, "
                f"p99={stats.get_response_time_percentile(0.99):.0f}ms, "
                f"failures={stats.num_failures}/{stats.num_requests})"
            )