# The TraceLake query gateway's HTTP interface.
openapi: 3.2.0
info:
  title: TraceLake query gateway
  version: '1'
  summary: Read an Iceberg-backed dataset over HTTP.
  description: |
    One endpoint, two request styles. `GET` takes a FIQL/RSQL filter in the query string.
    `POST` and `QUERY` take a JSON document and are the same in every respect. Both compile to
    the same query, so they share every validation rule, every limit and every error code.

    The `200` body is streamed. Check it for two members besides `rows`:

    - `error`, after `rows`: the query failed after the status line went out. The rows are partial.
    - `hotTier`, before `rows`: the dataset's hot source could not be read. Rows after
      `hotTier.boundary` are missing.

    Send `Accept-Encoding` to get a compressed body: `zstd`, `br` or `gzip`. When the q-values
    are equal, the gateway chooses `zstd`, then `br`, then `gzip`. The response then carries
    `Content-Encoding`. A decoded body has the same bytes as an uncompressed one, and it still
    streams. With no `Accept-Encoding`, or `identity` only, the body is not compressed. Responses
    carry `Vary: Accept-Encoding` also when they are not compressed.
servers:
  - url: /
    description: The gateway's `queryGateway.serverPort` (default 8080).
security:
  - bearer: []
tags:
  - name: query
    description: Read a dataset.
  - name: mcp
    description: The same reads, for an AI agent over the Model Context Protocol.

paths:
  /query/v1/dataset/{datasetName}:
    parameters:
      - name: datasetName
        in: path
        required: true
        description: A dataset in `ingestion.datasets`. Any other name is `404 DATASET_NOT_FOUND`.
        schema: {type: string}
    get:
      operationId: expressQuery
      tags: [query]
      summary: Express lookup (FIQL/RSQL filter in the query string)
      description: |
        Column names only; aggregate functions are `POST`/`QUERY`'s. Every parameter is optional:
        no parameters is every column, unfiltered, first page of 500 rows. An unknown parameter is
        a `400`. Behind a proxy, send FIQL's `;` (AND) as `%3B`.
      parameters: &getParameters
        - name: filter
          in: query
          description: FIQL/RSQL filter. At most 8 KiB (bytes), 32 levels of parentheses, expression depth 256.
          schema: {type: string}
          example: service_name==auth-api;duration_ms=gt=250
        - name: attributes
          in: query
          description: Comma-separated columns, or `*` alone. Absent means every column.
          schema: {type: string}
          example: trace_id,service_name,duration_ms
        - name: groupBy
          in: query
          description: Comma-separated columns. A `groupBy` with no aggregate is a DISTINCT.
          schema: {type: string}
        - name: orderBy
          in: query
          description: Comma-separated sort terms; a leading `-` sorts descending.
          schema: {type: string}
          example: service_name,-duration_ms
        - $ref: '#/components/parameters/page'
        - $ref: '#/components/parameters/limit'
        - $ref: '#/components/parameters/tier'
      responses: &responses
        '200': {$ref: '#/components/responses/Rows'}
        '400': {$ref: '#/components/responses/BadRequest'}
        '401': {$ref: '#/components/responses/Unauthorized'}
        '403': {$ref: '#/components/responses/Forbidden'}
        '404': {$ref: '#/components/responses/NotFound'}
        '405': {$ref: '#/components/responses/MethodNotAllowed'}
        '422': {$ref: '#/components/responses/Unprocessable'}
        '500': {$ref: '#/components/responses/Internal'}
        '501': {$ref: '#/components/responses/NotImplemented'}
        '503': {$ref: '#/components/responses/Unavailable'}
        '504': {$ref: '#/components/responses/Timeout'}
    head:
      operationId: expressQueryHead
      tags: [query]
      summary: The same as `GET`, without the body
      parameters: *getParameters
      responses: *responses
    post:
      operationId: analyticalQuery
      tags: [query]
      summary: Analytical document (JSON body)
      description: Everything `GET` does, plus aggregate function calls. Identical to `QUERY`.
      requestBody: {$ref: '#/components/requestBodies/QueryDocument'}
      responses: *responses
    query:
      operationId: analyticalQueryQuery
      tags: [query]
      summary: Analytical document (JSON body), as a safe and idempotent request
      description: |
        The HTTP `QUERY` method. The same as `POST` in every respect: body, limits, errors and
        response bytes. Use `POST` through an intermediary that allows only standard methods.
      requestBody: {$ref: '#/components/requestBodies/QueryDocument'}
      responses: *responses

  /mcp:
    post:
      operationId: mcp
      tags: [mcp]
      summary: Model Context Protocol endpoint (revision 2026-07-28, Streamable HTTP)
      description: |
        Served only when `queryGateway.mcp` is configured. One JSON-RPC request per POST, answered
        with one JSON object: `server/discover`, `tools/list` and `tools/call`. The tools are
        `help`, `list_datasets`, `describe_dataset` and `query`; `query` takes the `QueryDocument`
        plus `dataset`. The token's `aud` must be `queryGateway.mcp.resourceUrl`.
      requestBody:
        required: true
        content:
          application/json:
            schema: {type: object, description: A JSON-RPC 2.0 request.}
      responses:
        '200':
          description: A JSON-RPC response. A refused tool call is a result with `isError`.
          content:
            application/json:
              schema: {type: object}
        '202': {description: A JSON-RPC notification was accepted.}
        '400': {description: 'JSON-RPC error: parse error, header mismatch (-32020) or unsupported protocol version (-32022).'}
        '401':
          description: Missing or invalid token, or one whose `aud` is not this endpoint.
          headers:
            WWW-Authenticate:
              schema: {type: string, example: 'Bearer resource_metadata="https://gw.example.com/.well-known/oauth-protected-resource"'}
        '403': {description: An `Origin` other than the endpoint's own.}
        '404': {description: 'JSON-RPC error -32601: an unknown method.'}
        '405': {description: 'JSON-RPC error -32600 for any HTTP method other than POST, with `Allow: POST`.'}
        '503': {description: 'UPSTREAM_AUTH_UNAVAILABLE: the identity provider is unreachable. A busy pod is a tool error, not a 503.'}
  /.well-known/oauth-protected-resource:
    get:
      operationId: protectedResourceMetadata
      tags: [mcp]
      summary: OAuth 2.0 Protected Resource Metadata (RFC 9728) for the MCP endpoint
      description: Served without a token, only when `queryGateway.mcp` is configured.
      security: []
      responses:
        '200':
          description: The MCP endpoint and the issuer of its tokens.
          content:
            application/json:
              schema:
                type: object
                required: [resource, authorization_servers]
                properties:
                  resource: {type: string, format: uri}
                  authorization_servers: {type: array, items: {type: string, format: uri}}
                  bearer_methods_supported: {type: array, items: {type: string}}

components:
  securitySchemes:
    bearer:
      type: http
      scheme: bearer
      bearerFormat: JWT
      description: |
        An OIDC token, validated on every request (signature, expiry, issuer, audience, claims).
        There is no anonymous mode. Auth runs before dataset resolution.

  parameters:
    page:
      name: page
      in: query
      description: 0-based page index. A page whose row offset overflows is a `400`.
      schema: {type: integer, minimum: 0, default: 0}
    limit:
      name: limit
      in: query
      description: Rows per page. A value over 10000 is clamped to 10000, not refused.
      schema: {type: integer, minimum: 0, default: 500}
    tier:
      name: tier
      in: query
      description: |
        Read one tier only: `hot` (the dataset's hot source) or `cold` (Iceberg). Absent reads
        both, split at `T = now − hotSource.boundarySeconds`. `hot` on a dataset with no hot source
        is a `400`.
      schema: {$ref: '#/components/schemas/Tier'}

  requestBodies:
    QueryDocument:
      required: true
      description: |
        `Content-Type: application/json` is required; without it, or with a body that does not
        parse, the answer is `400 INVALID_QUERY_SYNTAX` with `target` `body`.
      content:
        application/json:
          schema: {$ref: '#/components/schemas/QueryDocument'}
          examples:
            errorsPerService:
              summary: Error count per service, worst first
              value:
                attributes: [service_name, {fn: count, arg: '*', as: errors}]
                filter: status=ge=500
                groupBy: [service_name]
                orderBy: [-errors]
                limit: 25

  headers:
    Cache-Control:
      description: Always `no-store` on an error.
      schema: {type: string, const: no-store}

  responses:
    Rows:
      description: |
        The rows, streamed. Members appear in this order: `hotTier` (only on a degraded answer),
        `rows`, `error` (only when the query failed after the status line went out). A response
        with `error` is partial.
      content:
        application/json:
          schema: {$ref: '#/components/schemas/Rows'}
          examples:
            rows:
              value: {rows: [{service_name: auth-api, errors: 412}, {service_name: billing, errors: 87}]}
            trailered:
              summary: Failed after the status line; partial
              value:
                rows: [{service_name: auth-api, errors: 412}]
                error: {code: STORAGE_INTERNAL_ERROR, message: the query could not be completed, target: spans, timestamp: '2026-08-08T10:04:12Z'}
            degraded:
              summary: The hot source could not be read; rows after the boundary are missing
              value:
                hotTier: {outcome: degraded, boundary: '2026-10-01T09:53:08.412907Z'}
                rows: [{service_name: auth-api, duration_ms: 412}]
    BadRequest:
      description: The request is malformed or names a disallowed column.
      headers: {Cache-Control: {$ref: '#/components/headers/Cache-Control'}}
      content:
        application/json:
          schema: {$ref: '#/components/schemas/Error'}
          examples:
            INVALID_QUERY_SYNTAX:
              value: {error: {code: INVALID_QUERY_SYNTAX, message: the query filter could not be parsed, target: filter, timestamp: '2026-08-07T16:11:15Z'}}
            INPUT_MALICIOUS:
              value: {error: {code: INPUT_MALICIOUS, message: a column name contains disallowed characters, target: user-id, timestamp: '2026-08-07T16:11:15Z'}}
    Unauthorized:
      description: Missing, expired or invalid token.
      headers:
        Cache-Control: {$ref: '#/components/headers/Cache-Control'}
        WWW-Authenticate:
          schema: {type: string, const: Bearer}
      content:
        application/json:
          schema: {$ref: '#/components/schemas/Error'}
          examples:
            UNAUTHORIZED:
              value: {error: {code: UNAUTHORIZED, message: a valid bearer token is required, target: '', timestamp: '2026-08-07T16:11:15Z'}}
    Forbidden:
      description: The token's role is not authorized for the dataset, or the dataset is in no `datasetRoles` entry.
      headers: {Cache-Control: {$ref: '#/components/headers/Cache-Control'}}
      content:
        application/json:
          schema: {$ref: '#/components/schemas/Error'}
          examples:
            FORBIDDEN:
              value: {error: {code: FORBIDDEN, message: this token's role is not authorized for this dataset, target: spans, timestamp: '2026-08-07T16:11:15Z'}}
    NotFound:
      description: The dataset is not configured, or the URL matches no route; then `target` is the path.
      headers: {Cache-Control: {$ref: '#/components/headers/Cache-Control'}}
      content:
        application/json:
          schema: {$ref: '#/components/schemas/Error'}
          examples:
            DATASET_NOT_FOUND:
              value: {error: {code: DATASET_NOT_FOUND, message: no such dataset, target: nope, timestamp: '2026-08-07T16:11:15Z'}}
    MethodNotAllowed:
      description: Any method other than GET, HEAD, POST and QUERY. No body.
      headers:
        Allow:
          schema: {type: string, const: 'GET, HEAD, POST, QUERY'}
    Unprocessable:
      description: Well-formed, but over a limit a narrower range or an aggregate avoids.
      headers: {Cache-Control: {$ref: '#/components/headers/Cache-Control'}}
      content:
        application/json:
          schema: {$ref: '#/components/schemas/Error'}
          examples:
            WINDOW_CAP_EXCEEDED:
              value: {error: {code: WINDOW_CAP_EXCEEDED, message: raw extraction exceeds this dataset's maximum time window; narrow the range or aggregate, target: spans, timestamp: '2026-08-07T16:11:15Z'}}
            MANIFEST_BUDGET_EXCEEDED:
              value: {error: {code: MANIFEST_BUDGET_EXCEEDED, message: the query needs more decoded table metadata than this gateway may hold at once; narrow the partition or time range, target: spans, timestamp: '2026-08-07T16:11:15Z'}}
    Internal:
      description: An object-store fault, or a query the engine could not execute, before the status line.
      headers: {Cache-Control: {$ref: '#/components/headers/Cache-Control'}}
      content:
        application/json:
          schema: {$ref: '#/components/schemas/Error'}
          examples:
            STORAGE_INTERNAL_ERROR:
              value: {error: {code: STORAGE_INTERNAL_ERROR, message: the query could not be completed, target: '', timestamp: '2026-08-07T16:11:15Z'}}
    NotImplemented:
      description: |
        The dataset's snapshot carries row-level delete files, which the gateway does not apply. Permanent
        until another engine compacts the deletes away; retrying does not help.
      headers: {Cache-Control: {$ref: '#/components/headers/Cache-Control'}}
      content:
        application/json:
          schema: {$ref: '#/components/schemas/Error'}
          examples:
            DELETE_FILES_UNSUPPORTED:
              value: {error: {code: DELETE_FILES_UNSUPPORTED, message: "this dataset's table carries row-level delete files, which this gateway does not apply", target: spans, timestamp: '2026-08-07T16:11:15Z'}}
    Unavailable:
      description: A dependency or the pod's query slots are unavailable. Retry shortly.
      headers: {Cache-Control: {$ref: '#/components/headers/Cache-Control'}}
      content:
        application/json:
          schema: {$ref: '#/components/schemas/Error'}
          examples:
            UPSTREAM_AUTH_UNAVAILABLE:
              value: {error: {code: UPSTREAM_AUTH_UNAVAILABLE, message: the identity provider is unreachable; retry shortly, target: '', timestamp: '2026-08-07T16:11:15Z'}}
            QUERY_CONCURRENCY_EXCEEDED:
              value: {error: {code: QUERY_CONCURRENCY_EXCEEDED, message: this gateway is running as many queries as it may; retry shortly, target: '', timestamp: '2026-08-07T16:11:15Z'}}
            CATALOG_UNAVAILABLE:
              value: {error: {code: CATALOG_UNAVAILABLE, message: table state is temporarily unresolvable; retry shortly, target: spans, timestamp: '2026-08-07T16:11:15Z'}}
            TABLE_NOT_CREATED:
              value: {error: {code: TABLE_NOT_CREATED, message: "this dataset's table has not been created yet; retry shortly", target: spans, timestamp: '2026-08-07T16:11:15Z'}}
            HOT_SOURCE_UNAVAILABLE:
              value: {error: {code: HOT_SOURCE_UNAVAILABLE, message: the dataset's hot source could not be read; retry shortly, target: spans, timestamp: '2026-08-07T16:11:15Z'}}
    Timeout:
      description: Planning and pruning exceeded `queryGateway.queryTimeoutSeconds`.
      headers: {Cache-Control: {$ref: '#/components/headers/Cache-Control'}}
      content:
        application/json:
          schema: {$ref: '#/components/schemas/Error'}
          examples:
            COMPUTE_TIMEOUT:
              value: {error: {code: COMPUTE_TIMEOUT, message: the query did not complete within the compute deadline, target: spans, timestamp: '2026-08-07T16:11:15Z'}}

  schemas:
    Tier:
      type: string
      enum: [hot, cold]
    Column:
      description: A column name, group key, sort key or alias. A character outside the pattern is `400 INPUT_MALICIOUS`.
      type: string
      pattern: '^[a-zA-Z0-9_.]+$'
    Call:
      description: An aggregate in the projection. `arg` `*` is accepted by `count` only.
      type: object
      additionalProperties: false
      required: [fn, arg, as]
      properties:
        fn: {type: string, enum: [count, sum, avg, min, max]}
        arg: {type: string}
        as: {$ref: '#/components/schemas/Column'}
    QueryDocument:
      description: Every field is optional; `{}` is every column, unfiltered, first page of 500 rows.
      type: object
      additionalProperties: false
      properties:
        format:
          description: '`rows` only. `trace_graph` is not supported yet and is refused with `400`, `target` `format`.'
          type: string
          enum: [rows, trace_graph]
          default: rows
        attributes:
          description: Columns, `*` alone, and/or calls. Absent means every column.
          type: array
          items:
            oneOf:
              - type: string
              - $ref: '#/components/schemas/Call'
        filter:
          description: FIQL/RSQL filter, as for `GET`, with the same limits.
          type: string
        groupBy:
          type: array
          items: {$ref: '#/components/schemas/Column'}
        orderBy:
          description: Sort terms; a leading `-` sorts descending.
          type: array
          items: {type: string}
        page: {type: integer, minimum: 0, default: 0}
        limit:
          description: Rows per page. A value over 10000 is clamped to 10000.
          type: integer
          minimum: 0
          default: 500
        tier: {$ref: '#/components/schemas/Tier'}
    Rows:
      type: object
      additionalProperties: false
      required: [rows]
      properties:
        hotTier: {$ref: '#/components/schemas/HotTier'}
        rows:
          description: One object per row, keyed by column name or alias, in `attributes` order.
          type: array
          items: {type: object}
        error: {$ref: '#/components/schemas/ErrorObject'}
    HotTier:
      description: Present only on a degraded answer. Every row after `boundary` is missing.
      type: object
      additionalProperties: false
      required: [outcome, boundary]
      properties:
        outcome: {type: string, enum: [degraded]}
        boundary: {type: string, format: date-time}
    Error:
      type: object
      additionalProperties: false
      required: [error]
      properties:
        error: {$ref: '#/components/schemas/ErrorObject'}
    ErrorObject:
      description: Internals-free by contract; no stack traces, SQL, object-store paths or parse positions.
      type: object
      additionalProperties: false
      required: [code, message, target, timestamp]
      properties:
        code: {$ref: '#/components/schemas/ErrorCode'}
        message: {type: string}
        target:
          description: The offending dataset, column, operator or parameter; `""` when there is none.
          type: string
        timestamp: {type: string, format: date-time}
        details:
          description: Optional in the contract. No error carries it today.
    ErrorCode:
      type: string
      enum:
        - INVALID_QUERY_SYNTAX
        - INPUT_MALICIOUS
        - UNAUTHORIZED
        - FORBIDDEN
        - DATASET_NOT_FOUND
        - WINDOW_CAP_EXCEEDED
        - MANIFEST_BUDGET_EXCEEDED
        - STORAGE_INTERNAL_ERROR
        - DELETE_FILES_UNSUPPORTED
        - UPSTREAM_AUTH_UNAVAILABLE
        - QUERY_CONCURRENCY_EXCEEDED
        - CATALOG_UNAVAILABLE
        - TABLE_NOT_CREATED
        - HOT_SOURCE_UNAVAILABLE
        - COMPUTE_TIMEOUT
