> ## Documentation Index
> Fetch the complete documentation index at: https://docs.gp.scale.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Get time-bucketed span metrics

> Compute time-bucketed span metrics over the requested window and filters.

``metrics`` optionally selects count, errors, or latency (p50/p75/p95);
omitting it preserves the all-metrics response. ``bucket_minutes`` sets the
requested bucket size, but the effective
size is enlarged automatically so the response never exceeds 100 buckets (the
value actually used is returned in ``bucket_minutes``). Both ``from_ts`` and
``to_ts`` are required. A reversed time window (``from_ts`` after ``to_ts``) is
rejected with 422. The underlying scan is capped at 50,000 matching spans,
so metrics over a very large window may be based on a truncated set. Results
are narrowed to traces the caller is authorized to read.

When the tracing service serves the read, percentiles are exact on Postgres
deployments and approximate estimates on ClickHouse deployments; durations are
derived from microsecond timestamps on Postgres, so a value can differ by one
millisecond at a boundary. On Postgres deployments the exact percentiles sort the
matching rows in memory: a by-span request, or a metrics request whose
``bucket_minutes`` spans the whole window, over a window larger than the
deployment's work memory and temp-file bound is refused rather than degraded, with
400 ``QUERY_TEMP_FILE_LIMIT_EXCEEDED`` and the tracing service's detail, with or
without ``search_texts`` and on either read source, never as a fallback to the
legacy Postgres store. Narrow the time window or filters; ClickHouse deployments
never return that code.

``x-project-id`` narrows the result to traces whose root span carries that project,
when ``PROJECT_SCOPED_SPAN_LISTING`` is on for the account, on either store.



## OpenAPI

````yaml /openapi/v5.yaml post /v5/spans/metrics
openapi: 3.1.0
info:
  title: EGP API V5
  description: >-
    This is the parent API for all EGP APIs. If you are looking for the EGP API,
    please go to https://api.egp.scale.com/docs.
  contact:
    name: Scale Generative AI Platform
    url: https://scale.com/genai-platform
  version: 0.1.0
servers:
  - url: https://api.egp.scale.com
security: []
paths:
  /v5/spans/metrics:
    post:
      tags:
        - Spans
      summary: Get time-bucketed span metrics
      description: >-
        Compute time-bucketed span metrics over the requested window and
        filters.


        ``metrics`` optionally selects count, errors, or latency (p50/p75/p95);

        omitting it preserves the all-metrics response. ``bucket_minutes`` sets
        the

        requested bucket size, but the effective

        size is enlarged automatically so the response never exceeds 100 buckets
        (the

        value actually used is returned in ``bucket_minutes``). Both ``from_ts``
        and

        ``to_ts`` are required. A reversed time window (``from_ts`` after
        ``to_ts``) is

        rejected with 422. The underlying scan is capped at 50,000 matching
        spans,

        so metrics over a very large window may be based on a truncated set.
        Results

        are narrowed to traces the caller is authorized to read.


        When the tracing service serves the read, percentiles are exact on
        Postgres

        deployments and approximate estimates on ClickHouse deployments;
        durations are

        derived from microsecond timestamps on Postgres, so a value can differ
        by one

        millisecond at a boundary. On Postgres deployments the exact percentiles
        sort the

        matching rows in memory: a by-span request, or a metrics request whose

        ``bucket_minutes`` spans the whole window, over a window larger than the

        deployment's work memory and temp-file bound is refused rather than
        degraded, with

        400 ``QUERY_TEMP_FILE_LIMIT_EXCEEDED`` and the tracing service's detail,
        with or

        without ``search_texts`` and on either read source, never as a fallback
        to the

        legacy Postgres store. Narrow the time window or filters; ClickHouse
        deployments

        never return that code.


        ``x-project-id`` narrows the result to traces whose root span carries
        that project,

        when ``PROJECT_SCOPED_SPAN_LISTING`` is on for the account, on either
        store.
      operationId: POST-V5-/v5/spans/metrics
      parameters:
        - name: from_ts
          in: query
          required: false
          schema:
            anyOf:
              - type: string
                format: date-time
              - type: 'null'
            description: The starting (oldest) timestamp in ISO format.
            title: From Ts
          description: The starting (oldest) timestamp in ISO format.
        - name: to_ts
          in: query
          required: false
          schema:
            anyOf:
              - type: string
                format: date-time
              - type: 'null'
            description: The ending (most recent) timestamp in ISO format.
            title: To Ts
          description: The ending (most recent) timestamp in ISO format.
        - name: x-selected-account-id
          in: header
          required: false
          schema:
            anyOf:
              - type: string
              - type: 'null'
            title: Account ID Header
        - name: x-project-id
          in: header
          required: false
          schema:
            anyOf:
              - type: string
              - type: 'null'
            title: Project ID Header
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/SpansMetricsRequest'
      responses:
        '200':
          description: Successful Response
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/SpansMetricsResponse'
        '400':
          description: >-
            The request carried a value this API or the tracing service
            rejected, such as a search term breaking a documented rule or a
            malformed pagination cursor.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/SpanReadErrorResponse'
        '422':
          description: >-
            A malformed request returns the validation error shape, one entry
            per offending field. A request this API refuses returns only detail,
            as when x-project-id is sent for an account whose tracing backend
            cannot apply the project scope.
          content:
            application/json:
              schema:
                anyOf:
                  - $ref: '#/components/schemas/HTTPValidationError'
                  - $ref: '#/components/schemas/SpanReadErrorResponse'
        '503':
          description: >-
            The configured tracing read backend is unavailable. Known service
            configuration failures include a stable error_code; other failures
            return only detail.
          headers:
            x-correlation-id:
              description: Correlation ID for this request.
              schema:
                type: string
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/SpanReadErrorResponse'
      security:
        - APIKeyHeader: []
components:
  schemas:
    SpansMetricsRequest:
      properties:
        parents_only:
          anyOf:
            - type: boolean
            - type: 'null'
          title: Parents Only
          description: Only fetch spans that are the top-level (ie. have no parent_id)
        span_ids:
          anyOf:
            - items:
                type: string
              type: array
            - type: 'null'
          title: Span Ids
          description: Filter by span IDs
        trace_ids:
          anyOf:
            - items:
                type: string
              type: array
            - type: 'null'
          title: Trace Ids
          description: >-
            Filter by trace IDs. The combined count of trace_ids, span_ids,
            excluded_span_ids, excluded_trace_ids, parent_ids, and (trace_id,
            span_id) pairs (each pair counting 2) may not exceed 10000. A
            request over that returns 422.
        excluded_span_ids:
          anyOf:
            - items:
                type: string
              type: array
            - type: 'null'
          title: Excluded Span Ids
          description: List of span IDs to exclude from results
        excluded_trace_ids:
          anyOf:
            - items:
                type: string
              type: array
            - type: 'null'
          title: Excluded Trace Ids
          description: List of trace IDs to exclude from results
        spans:
          anyOf:
            - items:
                $ref: '#/components/schemas/SpanRef'
              type: array
            - type: 'null'
          title: Spans
          description: >-
            Filter by exact (trace_id, span_id) identity. Unlike span_ids, a
            pair never matches a same-id span from another trace. ANDs with
            span_ids when both are set.
        excluded_spans:
          anyOf:
            - items:
                $ref: '#/components/schemas/SpanRef'
              type: array
            - type: 'null'
          title: Excluded Spans
          description: >-
            List of (trace_id, span_id) identities to exclude from results.
            Unlike excluded_span_ids, a pair never excludes a same-id span from
            another trace. Takes precedence over excluded_span_ids when both are
            set.
        group_id:
          anyOf:
            - type: string
            - type: 'null'
          title: Group Id
          description: Filter by group ID
        parent_ids:
          anyOf:
            - items:
                type: string
              type: array
            - type: 'null'
          title: Parent Ids
          description: Filter to the direct children of any of these parent span IDs
        names:
          anyOf:
            - items:
                type: string
              type: array
            - type: 'null'
          title: Names
          description: Filter by trace/span name
        statuses:
          anyOf:
            - items:
                $ref: '#/components/schemas/ApplicationOperationStatus'
              type: array
            - type: 'null'
          title: Statuses
          description: Filter on span status
        types:
          anyOf:
            - items:
                $ref: '#/components/schemas/ApplicationOperationType'
              type: array
            - type: 'null'
          title: Types
        search_texts:
          anyOf:
            - items:
                type: string
              type: array
            - type: 'null'
          title: Search Texts
          description: >-
            Case-insensitive text search across span name, input, output, and
            metadata. A single-word term of ASCII letters and digits matches as
            a whole word in input, output, and metadata, and as a substring of
            the name. A term of up to 8 such words matches as a contiguous
            phrase whose words each appear as whole words. All other terms
            (punctuated, non-ASCII, longer) match as substrings, where mid-word
            fragments match and an inflected form such as a plural matches only
            where it appears literally. Wrapping a term in double quotes makes
            it a phrase: the quotes mark the phrase and are never matched, a
            backslash escapes a quote or a backslash inside them, the phrase
            must appear contiguously inside one searched value (the input, the
            output, or the metadata), a phrase of up to 8 ASCII letter-and-digit
            words additionally requires each of those words to appear there as a
            whole word, and a UUID-shaped phrase stays a text search. A term
            whose quote is unterminated or left unescaped mid-term is matched
            literally, quotes included. Multiple terms are ANDed, and
            UUID-shaped terms match trace IDs instead. A span must match every
            non-UUID term, and each term may match any of the searched fields.
            UUID matches are ORed onto the text match. Each term must be at
            least 2 characters, measured between the quotes and ignoring outer
            whitespace for a phrase, and at most 10 terms are supported. For
            exact trace ID lookup, use the `trace_ids` filter. The tracing
            service runs on either ClickHouse or Postgres, and the two engines
            match differently. On Postgres deployments the whole-word match uses
            the simple text-search parser, which keeps hosts, e-mail addresses,
            file paths, version strings, hyphenated compounds, URLs and query
            strings as single words (https://x.com/path?q=1 yields
            x.com/path?q=1, x.com and /path?q=1, never path, q or 1;
            user@example.com and v1.2.3 are one word each; gpt-4o yields the
            compound and its parts), whereas ClickHouse deployments split on
            every non-alphanumeric ASCII byte. A single word inside such a value
            is a whole-word hit on ClickHouse and a miss on Postgres; the
            substring forms behave identically on both. On Postgres deployments
            a value over 80000 bytes has only its first 20000 characters indexed
            for whole-word matching; text past that is reachable only by the
            substring forms. Words longer than 2047 bytes are matched as
            substrings, never as whole words. Case folding of non-ASCII text
            follows the database's LC_CTYPE on Postgres deployments, for the
            whole-word index, the quoted-phrase and substring forms and the
            word-boundary check alike; under a C-locale database non-ASCII
            letters are not folded. ASCII folds everywhere. Input and output
            behave identically on both engines. A substring-form term, or a
            text-filtered metrics request, reads every row of the time window
            that survives the other filters. A term that matches too many rows
            in the window is refused by the tracing service as QUERY_TOO_BROAD,
            at an engine-specific threshold, and on Postgres deployments a read
            whose sorts or hashes, the text candidate sets included, outgrow the
            deployment's work memory and its temp-file bound is refused as
            QUERY_TEMP_FILE_LIMIT_EXCEEDED, a code ClickHouse deployments never
            return and one a read without text can also earn. This API relays
            either refusal as a 400 carrying the tracing service's detail, never
            as a page from the legacy trace store, and an export's refusal is
            reported as the failed export's reason on the export status, not on
            the POST. On Postgres deployments each term is counted on its own,
            in every class (whole word, phrase and substring alike) and on every
            read that carries text, and is refused when it alone matches more
            than 50000 rows of the window that survive the other filters, with
            or without assessment_types. On ClickHouse deployments the refusal
            is the candidate-set cap, a deployment-configured limit counted over
            the matches of all terms together: a search page bounds its
            candidates to the page, so there the cap is a backstop rather than a
            limit a common term meets; metrics and by-span resolve every match
            and can trip it; and an export runs under its own 2000000-row set
            cap on every request, assessment_types included. Accounts still
            served by the legacy trace store match differently until migrated:
            every term matches as stemmed whole words (so inflected forms match
            and multi-word terms match word-adjacent), only input and output are
            searched, the 2-character minimum is not enforced, quoting a term
            changes nothing (the quotes are stripped and a multi-word term is
            already matched word-adjacent), and characters like `:`, `|`, or `!`
            inside a term may be interpreted as query operators or cause an
            error.
        extra_metadata:
          anyOf:
            - additionalProperties: true
              type: object
            - type: 'null'
          title: Extra Metadata
          description: >-
            Filter on custom metadata: each key must equal its value, or any
            value of an array, and keys are ANDed. On the ClickHouse read path
            `$or` and `$and` also compose nested groups of predicates. On
            Postgres a `$`-prefixed key is an ordinary metadata key matched
            literally. Array values match element-wise; a negative zero inside
            an array equals zero on Postgres-served accounts and not on
            ClickHouse-served ones.
        application_variant_ids:
          anyOf:
            - items:
                type: string
              type: array
            - type: 'null'
          title: Application Variant Ids
          description: Filter by application variant IDs
        assessment_types:
          anyOf:
            - items:
                type: string
              type: array
            - type: 'null'
          title: Assessment Types
          description: Filter to spans that have at least one assessment of these types
        acp_types:
          anyOf:
            - items:
                type: string
              type: array
            - type: 'null'
          title: Acp Types
          description: Filter by ACP types
        agentex_agent_names:
          anyOf:
            - items:
                type: string
              type: array
            - type: 'null'
          title: Agentex Agent Names
          description: Filter by Agentex agent names
        agentex_agent_ids:
          anyOf:
            - items:
                type: string
              type: array
            - type: 'null'
          title: Agentex Agent Ids
          description: Filter by Agentex agent IDs
        obs_trace_ids:
          anyOf:
            - items:
                type: string
              type: array
            - type: 'null'
          title: Obs Trace Ids
          description: >-
            Filter to the business spans that executed in any of these
            observability traces (the obs-to-business reverse lookup). Each id
            must be 32 lowercase hex characters. Served only by the sgp-traces
            service, so a request using this filter against an account still on
            the legacy store returns 422 rather than silently ignoring it.
        obs_span_ids:
          anyOf:
            - items:
                type: string
              type: array
            - type: 'null'
          title: Obs Span Ids
          description: >-
            Filter to the business spans that executed in any of these
            observability spans. Each id must be 16 lowercase hex characters. A
            W3C span id is unique per trace only, so combine with obs_trace_ids
            for exact identity, the same looseness span_ids carries versus the
            spans pair filter. ANDs with obs_trace_ids when both are set. Served
            only by the sgp-traces service, so a request using this filter
            against an account still on the legacy store returns 422 rather than
            silently ignoring it.
        min_duration_ms:
          anyOf:
            - type: integer
            - type: 'null'
          title: Min Duration Ms
          description: >-
            Minimum span duration in milliseconds (inclusive). Matched on
            completed duration, so a span with no end time is not reliably
            returned: fetch it by its own id or in its trace's span list.
        max_duration_ms:
          anyOf:
            - type: integer
            - type: 'null'
          title: Max Duration Ms
          description: >-
            Maximum span duration in milliseconds (inclusive). Matched on
            completed duration, so a span with no end time is never returned:
            fetch it by its own id or in its trace's span list.
        bucket_minutes:
          type: integer
          title: Bucket Minutes
          description: Size of each time bucket in minutes
          default: 30
        metrics:
          items:
            $ref: '#/components/schemas/SpanMetric'
          type: array
          title: Metrics
          description: >-
            Metric groups to compute. Omit or pass an empty list to compute all
            groups.
      type: object
      title: SpansMetricsRequest
    SpansMetricsResponse:
      properties:
        items:
          items:
            $ref: '#/components/schemas/SpansMetricsBucket'
          type: array
          title: Items
        bucket_minutes:
          type: integer
          title: Bucket Minutes
          description: Effective bucket size in minutes
          default: 30
        sampling:
          anyOf:
            - $ref: '#/components/schemas/SpansSamplingInfo'
            - type: 'null'
          description: >-
            How this aggregation was computed when trace-hash sampling is
            enabled, absent when sampling is disabled. Sampling is a ClickHouse
            mechanism of the tracing service: a response from its Postgres
            engine, or from the legacy trace store, never carries this field.
      type: object
      required:
        - items
      title: SpansMetricsResponse
    SpanReadErrorResponse:
      properties:
        detail:
          type: string
          title: Detail
          description: A user-safe explanation of why the tracing read failed.
        error_code:
          anyOf:
            - type: string
              const: TRACES_SERVICE_CONFIGURATION_ERROR
            - type: 'null'
          title: Error Code
          description: >-
            Stable classification for a known EGP-to-tracing-service
            configuration failure. Omitted when the downstream failure is not
            safely classifiable.
      type: object
      required:
        - detail
      title: SpanReadErrorResponse
      description: Safe public error body for a tracing read that could not be completed.
    HTTPValidationError:
      properties:
        detail:
          items:
            $ref: '#/components/schemas/ValidationError'
          type: array
          title: Detail
      type: object
      title: HTTPValidationError
    SpanRef:
      properties:
        trace_id:
          type: string
          title: Trace Id
          description: Trace ID of the referenced span
        span_id:
          type: string
          title: Span Id
          description: Span ID of the referenced span
      type: object
      required:
        - trace_id
        - span_id
      title: SpanRef
      description: >-
        One span addressed by its full identity, since span ids are only unique
        within a trace.
    ApplicationOperationStatus:
      type: string
      enum:
        - SUCCESS
        - ERROR
        - CANCELED
      title: ApplicationOperationStatus
    ApplicationOperationType:
      type: string
      enum:
        - TEXT_INPUT
        - TEXT_OUTPUT
        - COMPLETION_INPUT
        - COMPLETION
        - KB_RETRIEVAL
        - KB_INPUT
        - RERANKING
        - EXTERNAL_ENDPOINT
        - PROMPT_ENGINEERING
        - DOCUMENT_INPUT
        - MAP_REDUCE
        - DOCUMENT_SEARCH
        - DOCUMENT_PROMPT
        - CUSTOM
        - CODE_EXECUTION
        - DATA_MANIPULATION
        - EVALUATION
        - FILE_RETRIEVAL
        - KB_ADD_CHUNK
        - KB_MANAGEMENT
        - GUARDRAIL
        - OUTPUT_GUARDRAIL
        - TRACER
        - AGENT_TRACER
        - AGENT_WORKFLOW
        - STANDALONE
      title: ApplicationOperationType
    SpanMetric:
      type: string
      enum:
        - count
        - errors
        - latency
      title: SpanMetric
      description: An independently loadable metric group for the traces chart.
    SpansMetricsBucket:
      properties:
        bucket_start:
          type: string
          format: date-time
          title: Bucket Start
        count:
          anyOf:
            - type: integer
            - type: 'null'
          title: Count
        error_count:
          anyOf:
            - type: integer
            - type: 'null'
          title: Error Count
        p50_ms:
          anyOf:
            - type: number
            - type: 'null'
          title: P50 Ms
        p75_ms:
          anyOf:
            - type: number
            - type: 'null'
          title: P75 Ms
        p95_ms:
          anyOf:
            - type: number
            - type: 'null'
          title: P95 Ms
        approximate:
          anyOf:
            - type: boolean
            - type: 'null'
          title: Approximate
          description: >-
            True when this bucket carried fewer sampled traces than the accuracy
            floor, or when the sample read none of it at all, so its count and
            percentiles are not usable as measured values. Absent on an exact
            response. error_count stays exact either way.
      type: object
      required:
        - bucket_start
      title: SpansMetricsBucket
    SpansSamplingInfo:
      properties:
        sampled:
          type: boolean
          title: Sampled
          description: >-
            True when the response was computed from a trace-hash sample rather
            than every in-window row.
        path:
          $ref: '#/components/schemas/SpansSamplingPath'
          description: Execution path that served the response.
        fraction:
          type: number
          title: Fraction
          description: >-
            Effective sampling fraction in (0, 1], 1 when the response is exact.
            Whole traces sample in or out together, so trace-level aggregates
            stay valid.
        sampled_rows:
          type: integer
          title: Sampled Rows
          description: >-
            Rows the sampled pass read after filters, before scaling. 0 when the
            response was served exact without a sampled pass.
        sampled_traces:
          type: integer
          title: Sampled Traces
          description: >-
            Distinct traces the sampled pass read, the accuracy driver (count
            margin ~ 1/sqrt(sampled traces in a cell)).
        panel_fractions:
          anyOf:
            - additionalProperties:
                type: number
              type: object
            - type: 'null'
          title: Panel Fractions
          description: >-
            Per-panel effective fractions, present only if panels within one
            request sampled at different fractions.
        percentiles_approximate:
          anyOf:
            - type: boolean
            - type: 'null'
          title: Percentiles Approximate
          description: >-
            True when the percentiles came from the sampled statement's sketch,
            including on the exact path. A sketch's percentiles can differ from
            an unsampled run over the same rows even when the sample read every
            row. Counts, sums and means are unaffected and stay exact on that
            path.
      type: object
      required:
        - sampled
        - path
        - fraction
        - sampled_rows
        - sampled_traces
      title: SpansSamplingInfo
      description: >-
        How a sampled-capable aggregation read served its response. Counts scale
        by 1/fraction, while averages, percentiles, and ratios weigh each row by
        its own shard's factor. Error counts are always exact, and min/max
        durations are observed sample values, so on a sampled response max_ms is
        a lower bound of the true maximum.
    ValidationError:
      properties:
        loc:
          items:
            anyOf:
              - type: string
              - type: integer
          type: array
          title: Location
        msg:
          type: string
          title: Message
        type:
          type: string
          title: Error Type
        input:
          title: Input
        ctx:
          type: object
          title: Context
          additionalProperties: true
      type: object
      required:
        - loc
        - msg
        - type
      title: ValidationError
    SpansSamplingPath:
      type: string
      enum:
        - sampled
        - exact
        - exact_fallback
        - exact_text_search
        - exact_sampling_unavailable
      title: SpansSamplingPath
      description: Which execution path served a sampled-capable aggregation read.
  securitySchemes:
    APIKeyHeader:
      type: apiKey
      in: header
      name: x-api-key

````