## Search spans

`spans.search(SpanSearchParams**kwargs)  -> SyncCursorPage[Span]`

**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

- `allow_short_pages: Optional[bool]`

  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.

- `ending_before: Optional[str]`

- `from_ts: Optional[Union[str, datetime]]`

  The starting (oldest) timestamp in ISO format.

- `limit: Optional[int]`

- `sort_by: Optional[str]`

- `sort_order: Optional[SortOrder]`

  - `"asc"`

  - `"desc"`

- `starting_after: Optional[str]`

- `to_ts: Optional[Union[str, datetime]]`

  The ending (most recent) timestamp in ISO format.

- `acp_types: Optional[Sequence[str]]`

  Filter by ACP types

- `agentex_agent_ids: Optional[Sequence[str]]`

  Filter by Agentex agent IDs

- `agentex_agent_names: Optional[Sequence[str]]`

  Filter by Agentex agent names

- `application_variant_ids: Optional[Sequence[str]]`

  Filter by application variant IDs

- `assessment_types: Optional[Sequence[str]]`

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

- `excluded_span_ids: Optional[Sequence[str]]`

  List of span IDs to exclude from results

- `excluded_spans: Optional[Iterable[ExcludedSpan]]`

  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.

  - `span_id: str`

    Span ID of the referenced span

  - `trace_id: str`

    Trace ID of the referenced span

- `excluded_trace_ids: Optional[Sequence[str]]`

  List of trace IDs to exclude from results

- `extra_metadata: Optional[Dict[str, object]]`

  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.

- `group_id: Optional[str]`

  Filter by group ID

- `max_duration_ms: Optional[int]`

  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.

- `min_duration_ms: Optional[int]`

  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: Optional[Sequence[str]]`

  Filter by trace/span name

- `obs_span_ids: Optional[Sequence[str]]`

  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.

- `obs_trace_ids: Optional[Sequence[str]]`

  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.

- `parent_ids: Optional[Sequence[str]]`

  Filter to the direct children of any of these parent span IDs

- `parents_only: Optional[bool]`

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

- `search_texts: Optional[Sequence[str]]`

  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.

- `span_ids: Optional[Sequence[str]]`

  Filter by span IDs

- `spans: Optional[Iterable[Span]]`

  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.

  - `span_id: str`

    Span ID of the referenced span

  - `trace_id: str`

    Trace ID of the referenced span

- `statuses: Optional[List[SpanStatus]]`

  Filter on span status

  - `"SUCCESS"`

  - `"ERROR"`

  - `"CANCELED"`

- `trace_ids: Optional[Sequence[str]]`

  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: Optional[List[SpanType]]`

  - `"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"`

- `x_project_id: Optional[str]`

### Returns

- `class Span: …`

  - `id: str`

  - `account_id: str`

  - `name: str`

  - `start_timestamp: datetime`

  - `trace_id: str`

    id for grouping traces together, uuid is recommended

  - `application_interaction_id: Optional[str]`

    The interaction ID this span belongs to

  - `application_variant_id: Optional[str]`

    The id of the application variant this span belongs to

  - `created_by: Optional[Identity]`

    The identity that created the entity.

    - `id: str`

    - `type: Literal["user", "service_account"]`

      - `"user"`

      - `"service_account"`

    - `object: Optional[Literal["identity"]]`

      - `"identity"`

  - `end_timestamp: Optional[datetime]`

  - `expected: Optional[Dict[str, object]]`

  - `group_id: Optional[str]`

    Reference to a group_id

  - `input: Optional[Dict[str, object]]`

  - `input_tokens: Optional[int]`

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

  - `metadata: Optional[Dict[str, object]]`

  - `object: Optional[Literal["span"]]`

    - `"span"`

  - `obs_span_id: Optional[str]`

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

  - `obs_trace_id: Optional[str]`

    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: Optional[Dict[str, object]]`

  - `output_tokens: Optional[int]`

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

  - `parent_id: Optional[str]`

    Reference to a parent span_id

  - `status: Optional[SpanStatus]`

    - `"SUCCESS"`

    - `"ERROR"`

    - `"CANCELED"`

  - `type: Optional[SpanType]`

    - `"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"`

### Example

```python
import os
from scale_gp_beta import SGPClient

client = SGPClient(
    api_key=os.environ.get("SGP_API_KEY"),  # This is the default and can be omitted
)
page = client.spans.search()
page = page.items[0]
print(page.id)
```

#### 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
}
```
