## Search spans

`client.Spans.Search(ctx, params) (*CursorPage[Span], error)`

**post** `/v5/spans/search`

Search and list spans matching a set of filters, returning a keyset-paginated page.

Filters in the request body include trace and span ids, names, statuses,
types, free-text search, metadata, duration bounds, and more, scoped to an
optional time window. Results are keyset-paginated on indexed columns rather
than offset-paginated, and `total` is not computed (it is always 0); use the
pagination cursors to page through results. Reads route to the legacy trace
store or the tracing service per account (with fallback to the legacy trace
store outside strict mode), and results are narrowed to traces the caller is authorized to
read — a filter that resolves to no authorized traces yields an empty page
rather than an error. A reversed time window (`from_ts` after `to_ts`) is
rejected with 422, as is a request whose combined `trace_ids`, `span_ids`,
`excluded_span_ids`, `excluded_trace_ids`, and `parent_ids` count exceeds
10000. `sort_by` accepts `start_timestamp`, `duration_ms`,
`input_tokens` and `output_tokens`; the token counts are read from usage
reported at ingest, and a span whose producer reported none sorts as zero, so
it lands last descending and first ascending. The two token sorts are rejected
for an account still served by the legacy trace store, which keeps no token count
to order by. Any other unsupported sort falls back to timestamp order there.
Spans sharing a sort key are ordered by `trace_id` and `id` bytewise on both
tracing-service engines. Text search tokenization, indexed-prefix, word-length,
locale and metadata-bytes behavior differs between Postgres and ClickHouse
deployments of the tracing service as the `search_texts` field describes.

`x-project-id` narrows the result to traces whose root span carries that project,
when `PROJECT_SCOPED_SPAN_LISTING` is on for the account. An account the tracing service
serves holds no project placement, so a request carrying the header is rejected with
422 there.

### Parameters

- `params SpanSearchParams`

  - `AllowShortPages param.Field[bool]`

    Query param: Return however many spans fit the server byte budget instead of a 400 SEARCH_RESULT_TOO_LARGE, reporting the rest through has_more plus next_cursor going forward or prev_cursor going back. Send it only if the client reads has_more, because under it a page shorter than limit no longer means the end of the list. Honored by the tracing service on either of its storage engines. Accounts still served by the legacy trace store ignore it and page by item count, where a short page still means the end of the list.

  - `EndingBefore param.Field[string]`

    Query param

  - `FromTs param.Field[Time]`

    Query param: The starting (oldest) timestamp in ISO format.

  - `Limit param.Field[int64]`

    Query param

  - `SortBy param.Field[string]`

    Query param

  - `SortOrder param.Field[SortOrder]`

    Query param

  - `StartingAfter param.Field[string]`

    Query param

  - `ToTs param.Field[Time]`

    Query param: The ending (most recent) timestamp in ISO format.

  - `AcpTypes param.Field[[]string]`

    Body param: Filter by ACP types

  - `AgentexAgentIDs param.Field[[]string]`

    Body param: Filter by Agentex agent IDs

  - `AgentexAgentNames param.Field[[]string]`

    Body param: Filter by Agentex agent names

  - `ApplicationVariantIDs param.Field[[]string]`

    Body param: Filter by application variant IDs

  - `AssessmentTypes param.Field[[]string]`

    Body param: Filter to spans that have at least one assessment of these types

  - `ExcludedSpanIDs param.Field[[]string]`

    Body param: List of span IDs to exclude from results

  - `ExcludedSpans param.Field[[]SpanSearchParamsExcludedSpan]`

    Body param: 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.

    - `SpanID string`

      Span ID of the referenced span

    - `TraceID string`

      Trace ID of the referenced span

  - `ExcludedTraceIDs param.Field[[]string]`

    Body param: List of trace IDs to exclude from results

  - `ExtraMetadata param.Field[map[string, any]]`

    Body param: 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.

  - `GroupID param.Field[string]`

    Body param: Filter by group ID

  - `MaxDurationMs param.Field[int64]`

    Body param: 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.

  - `MinDurationMs param.Field[int64]`

    Body param: 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.

  - `Names param.Field[[]string]`

    Body param: Filter by trace/span name

  - `ObsSpanIDs param.Field[[]string]`

    Body param: 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.

  - `ObsTraceIDs param.Field[[]string]`

    Body param: 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.

  - `ParentIDs param.Field[[]string]`

    Body param: Filter to the direct children of any of these parent span IDs

  - `ParentsOnly param.Field[bool]`

    Body param: Only fetch spans that are the top-level (ie. have no parent_id)

  - `SearchTexts param.Field[[]string]`

    Body param: 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; whether this API relays that refusal as a 400 or answers the page from the legacy trace store follows its read-routing rules, 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.

  - `SpanIDs param.Field[[]string]`

    Body param: Filter by span IDs

  - `Spans param.Field[[]SpanSearchParamsSpan]`

    Body param: 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.

    - `SpanID string`

      Span ID of the referenced span

    - `TraceID string`

      Trace ID of the referenced span

  - `Statuses param.Field[[]SpanStatus]`

    Body param: Filter on span status

    - `const SpanStatusSuccess SpanStatus = "SUCCESS"`

    - `const SpanStatusError SpanStatus = "ERROR"`

    - `const SpanStatusCanceled SpanStatus = "CANCELED"`

  - `TraceIDs param.Field[[]string]`

    Body param: 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.

  - `Types param.Field[[]SpanType]`

    Body param

    - `const SpanTypeTextInput SpanType = "TEXT_INPUT"`

    - `const SpanTypeTextOutput SpanType = "TEXT_OUTPUT"`

    - `const SpanTypeCompletionInput SpanType = "COMPLETION_INPUT"`

    - `const SpanTypeCompletion SpanType = "COMPLETION"`

    - `const SpanTypeKBRetrieval SpanType = "KB_RETRIEVAL"`

    - `const SpanTypeKBInput SpanType = "KB_INPUT"`

    - `const SpanTypeReranking SpanType = "RERANKING"`

    - `const SpanTypeExternalEndpoint SpanType = "EXTERNAL_ENDPOINT"`

    - `const SpanTypePromptEngineering SpanType = "PROMPT_ENGINEERING"`

    - `const SpanTypeDocumentInput SpanType = "DOCUMENT_INPUT"`

    - `const SpanTypeMapReduce SpanType = "MAP_REDUCE"`

    - `const SpanTypeDocumentSearch SpanType = "DOCUMENT_SEARCH"`

    - `const SpanTypeDocumentPrompt SpanType = "DOCUMENT_PROMPT"`

    - `const SpanTypeCustom SpanType = "CUSTOM"`

    - `const SpanTypeCodeExecution SpanType = "CODE_EXECUTION"`

    - `const SpanTypeDataManipulation SpanType = "DATA_MANIPULATION"`

    - `const SpanTypeEvaluation SpanType = "EVALUATION"`

    - `const SpanTypeFileRetrieval SpanType = "FILE_RETRIEVAL"`

    - `const SpanTypeKBAddChunk SpanType = "KB_ADD_CHUNK"`

    - `const SpanTypeKBManagement SpanType = "KB_MANAGEMENT"`

    - `const SpanTypeGuardrail SpanType = "GUARDRAIL"`

    - `const SpanTypeOutputGuardrail SpanType = "OUTPUT_GUARDRAIL"`

    - `const SpanTypeTracer SpanType = "TRACER"`

    - `const SpanTypeAgentTracer SpanType = "AGENT_TRACER"`

    - `const SpanTypeAgentWorkflow SpanType = "AGENT_WORKFLOW"`

    - `const SpanTypeStandalone SpanType = "STANDALONE"`

  - `XProjectID param.Field[string]`

    Header param

### Returns

- `type Span struct{…}`

  - `ID string`

  - `AccountID string`

  - `Name string`

  - `StartTimestamp Time`

  - `TraceID string`

    id for grouping traces together, uuid is recommended

  - `ApplicationInteractionID string`

    The interaction ID this span belongs to

  - `ApplicationVariantID string`

    The id of the application variant this span belongs to

  - `CreatedBy Identity`

    The identity that created the entity.

    - `ID string`

    - `Type IdentityType`

      - `const IdentityTypeUser IdentityType = "user"`

      - `const IdentityTypeServiceAccount IdentityType = "service_account"`

    - `Object IdentityObject`

      - `const IdentityObjectIdentity IdentityObject = "identity"`

  - `EndTimestamp Time`

  - `Expected map[string, any]`

  - `GroupID string`

    Reference to a group_id

  - `Input map[string, any]`

  - `InputTokens int64`

    Prompt tokens the producer reported for this span, absent when it reported none. Same quantity the input_tokens sort orders by.

  - `Metadata map[string, any]`

  - `Object SpanObject`

    - `const SpanObjectSpan SpanObject = "span"`

  - `ObsSpanID string`

    W3C span id of the observability span this span executed in.

  - `ObsTraceID string`

    W3C trace id of the observability trace this span executed in. Null for spans written without the edge, and for accounts still served by the legacy trace store.

  - `Output map[string, any]`

  - `OutputTokens int64`

    Completion tokens the producer reported for this span, absent when it reported none. Same quantity the output_tokens sort orders by.

  - `ParentID string`

    Reference to a parent span_id

  - `Status SpanStatus`

    - `const SpanStatusSuccess SpanStatus = "SUCCESS"`

    - `const SpanStatusError SpanStatus = "ERROR"`

    - `const SpanStatusCanceled SpanStatus = "CANCELED"`

  - `Type SpanType`

    - `const SpanTypeTextInput SpanType = "TEXT_INPUT"`

    - `const SpanTypeTextOutput SpanType = "TEXT_OUTPUT"`

    - `const SpanTypeCompletionInput SpanType = "COMPLETION_INPUT"`

    - `const SpanTypeCompletion SpanType = "COMPLETION"`

    - `const SpanTypeKBRetrieval SpanType = "KB_RETRIEVAL"`

    - `const SpanTypeKBInput SpanType = "KB_INPUT"`

    - `const SpanTypeReranking SpanType = "RERANKING"`

    - `const SpanTypeExternalEndpoint SpanType = "EXTERNAL_ENDPOINT"`

    - `const SpanTypePromptEngineering SpanType = "PROMPT_ENGINEERING"`

    - `const SpanTypeDocumentInput SpanType = "DOCUMENT_INPUT"`

    - `const SpanTypeMapReduce SpanType = "MAP_REDUCE"`

    - `const SpanTypeDocumentSearch SpanType = "DOCUMENT_SEARCH"`

    - `const SpanTypeDocumentPrompt SpanType = "DOCUMENT_PROMPT"`

    - `const SpanTypeCustom SpanType = "CUSTOM"`

    - `const SpanTypeCodeExecution SpanType = "CODE_EXECUTION"`

    - `const SpanTypeDataManipulation SpanType = "DATA_MANIPULATION"`

    - `const SpanTypeEvaluation SpanType = "EVALUATION"`

    - `const SpanTypeFileRetrieval SpanType = "FILE_RETRIEVAL"`

    - `const SpanTypeKBAddChunk SpanType = "KB_ADD_CHUNK"`

    - `const SpanTypeKBManagement SpanType = "KB_MANAGEMENT"`

    - `const SpanTypeGuardrail SpanType = "GUARDRAIL"`

    - `const SpanTypeOutputGuardrail SpanType = "OUTPUT_GUARDRAIL"`

    - `const SpanTypeTracer SpanType = "TRACER"`

    - `const SpanTypeAgentTracer SpanType = "AGENT_TRACER"`

    - `const SpanTypeAgentWorkflow SpanType = "AGENT_WORKFLOW"`

    - `const SpanTypeStandalone SpanType = "STANDALONE"`

### Example

```go
package main

import (
  "context"
  "fmt"

  "github.com/scaleapi/sgp-dev-go"
  "github.com/scaleapi/sgp-dev-go/option"
)

func main() {
  client := sgpdev.NewClient(
    option.WithAPIKey("My API Key"),
    option.WithAccountID("My Account ID"),
  )
  page, err := client.Spans.Search(context.TODO(), sgpdev.SpanSearchParams{

  })
  if err != nil {
    panic(err.Error())
  }
  fmt.Printf("%+v\n", page)
}
```

#### Response

```json
{
  "has_more": true,
  "items": [
    {
      "id": "id",
      "account_id": "account_id",
      "name": "name",
      "start_timestamp": "2019-12-27T18:11:19.117Z",
      "trace_id": "trace_id",
      "application_interaction_id": "application_interaction_id",
      "application_variant_id": "application_variant_id",
      "created_by": {
        "id": "id",
        "type": "user",
        "object": "identity"
      },
      "end_timestamp": "2019-12-27T18:11:19.117Z",
      "expected": {
        "foo": "bar"
      },
      "group_id": "group_id",
      "input": {
        "foo": "bar"
      },
      "input_tokens": 0,
      "metadata": {
        "foo": "bar"
      },
      "object": "span",
      "obs_span_id": "obs_span_id",
      "obs_trace_id": "obs_trace_id",
      "output": {
        "foo": "bar"
      },
      "output_tokens": 0,
      "parent_id": "parent_id",
      "status": "SUCCESS",
      "type": "TEXT_INPUT"
    }
  ],
  "total": 0,
  "effective_from_ts": "2019-12-27T18:11:19.117Z",
  "effective_to_ts": "2019-12-27T18:11:19.117Z",
  "limit": 0,
  "next_cursor": "next_cursor",
  "object": "list",
  "prev_cursor": "prev_cursor",
  "window_truncated": true
}
```
