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

# Diagnose data source

> Run a synchronous diagnostic query (`log_patterns` for Loki/VictoriaLogs, `metric_trends` for Prometheus). Used by Flashduty AI SRE for log-pattern clustering and time-series trend analysis. Long-running — up to 35 s.

## Restrictions

| Aspect      | Value                                                                     |
| ----------- | ------------------------------------------------------------------------- |
| Rate limits | **600 requests/minute**; **10 requests/second** per account               |
| Permissions | Any valid `app_key` (read-only; not gated by a specific permission class) |

## Usage

* This is a diagnostic / RCA endpoint, not a raw data query — pair it with `/monit/query/rows` when you need detailed rows.
* `operation` defaults from `ds_type`: `loki` / `victorialogs` → `log_patterns`, `prometheus` → `metric_trends`. Other sources must pass `operation` explicitly.
* `methods` selects the analyses to run; when omitted, `log_patterns` defaults to `pattern_snapshot + pattern_compare(previous_window)` and `metric_trends` defaults to `single_window_shape + window_compare(previous_window)`.
* `time_range` is in Unix seconds; missing or invalid values default to the last 15 minutes; a window wider than 6 hours is rejected.
* The request is forwarded over WebSocket to `monit-edge`. Long-running: the request may take up to \~30 s on the edge side plus webapi overhead. Set client timeouts to **at least 35 s**.
* `options.*` are upper-bounded by edge (`max_logs_scanned` ≤ 50 000, `max_patterns` ≤ 50, `examples_per_pattern` ≤ 3, `step_seconds` ∈ \[15, 300], `max_series` ≤ 200, `topk` ≤ 50, `timeout_seconds` ≤ 30).
* Two error layers as with `/monit/query/rows`: edge-level execution errors come back as HTTP 200 with an `error` object in the body — check both layers.
* Log examples are basic-redacted before being returned; expect `warnings: ["examples redacted"]`. Do not treat them as raw logs.


## OpenAPI

````yaml /api-reference/monitors.openapi.en.json post /monit/query/diagnose
openapi: 3.1.0
info:
  title: Flashduty Open API
  description: >-
    Public HTTP API for the Flashduty incident management platform — incidents,
    notification templates, channels, schedules, monitors, RUM, and platform
    administration. Every operation is authenticated with an `app_key` query
    parameter issued from the Flashduty console under Account → APP Keys.
    Responses follow a uniform envelope: `{ request_id, data }` on success, `{
    request_id, error }` on failure.
  version: 1.0.0
servers:
  - url: https://api.flashcat.cloud
    description: Flashduty Open API
security:
  - AppKeyAuth: []
tags:
  - name: Monitors/Alert rules
    description: >-
      Create, manage, and export monitor alert rules. Query rule counters and
      audit history.
  - name: Monitors/Data sources
    description: Manage monitoring data sources used by alert rules to query metrics.
  - name: Monitors/Rule sets
    description: >-
      Manage shared rule sets (rulesets) in the Monitors rule repository.
      Rulesets can be shared publicly or within an account.
  - name: Monitors/Diagnostics
    description: >-
      Diagnostic and query endpoints used by Flashduty AI SRE — ad-hoc data
      source queries, log/metric diagnostics, and target-side tool invocation.
  - name: Monitors/Monitor utilities
    description: Monitors service activation and data preview utilities.
paths:
  /monit/query/diagnose:
    post:
      tags:
        - Monitors/Diagnostics
      summary: Diagnose data source
      description: >-
        Run a synchronous diagnostic query (`log_patterns` for
        Loki/VictoriaLogs, `metric_trends` for Prometheus). Used by Flashduty AI
        SRE for log-pattern clustering and time-series trend analysis.
        Long-running — up to 35 s.
      operationId: monit-read-query-diagnose
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/DiagnoseRequest'
            example:
              account_id: 10001
              ds_type: victorialogs
              ds_name: vmlogs-read
              operation: log_patterns
              time_range:
                start: 1776847544
                end: 1776849344
              methods:
                - name: pattern_snapshot
                - name: pattern_compare
                  baseline: same_window_yesterday
              input:
                query: _stream:{status='500'}
              options:
                max_logs_scanned: 10000
                max_patterns: 20
                examples_per_pattern: 2
                timeout_seconds: 25
      responses:
        '200':
          description: Success
          content:
            application/json:
              schema:
                allOf:
                  - $ref: '#/components/schemas/SuccessEnvelope'
                  - type: object
                    properties:
                      data:
                        $ref: '#/components/schemas/DiagnoseResponse'
              example:
                request_id: 01HK8XQE3Z7JM2NTFQ5YJ8P9R4
                data:
                  operation: log_patterns
                  ds_type: victorialogs
                  ds_name: vmlogs-read
                  query: _stream:{status='500'}
                  window:
                    start: 1776847544
                    end: 1776849344
                  results:
                    - method: pattern_snapshot
                      window:
                        start: 1776847544
                        end: 1776849344
                      summary:
                        logs_scanned: 405
                        baseline_logs_scanned: 0
                        current_truncated: false
                        baseline_truncated: false
                        patterns_total: 2
                        returned_patterns: 2
                        new_patterns: 0
                        surging_patterns: 0
                        surging_threshold:
                          change_ratio_min: 3
                          count_min: 5
                      patterns:
                        - pattern_hash: 239fa5da
                          template: POST /api/v<number>/orders/<number> HTTP/<number>
                          count: 213
                          first_seen: 1776847562
                          last_seen: 1776849336
                          severity: unknown
                          approximate: false
                          sources:
                            - field: pod
                              value: order-api-7f69d8d9b6-m4x9n
                              count: 130
                          examples:
                            - POST /api/v<number>/orders/<number> HTTP/<number>
                      warnings:
                        - examples redacted
        '400':
          $ref: '#/components/responses/BadRequest'
        '401':
          $ref: '#/components/responses/Unauthorized'
        '429':
          $ref: '#/components/responses/TooManyRequests'
        '500':
          $ref: '#/components/responses/ServerError'
components:
  schemas:
    DiagnoseRequest:
      type: object
      required:
        - ds_type
        - ds_name
        - input
      properties:
        account_id:
          type: integer
          format: int64
          description: >-
            Optional consistency check. Must equal the authenticated account
            when supplied.
        ds_type:
          type: string
          description: >-
            Data source type. `log_patterns` supports `loki` and `victorialogs`;
            `metric_trends` supports `prometheus`.
        ds_name:
          type: string
          description: Data source name configured under the tenant.
        operation:
          type: string
          enum:
            - log_patterns
            - metric_trends
          description: >-
            Diagnostic operation. When omitted, inferred from `ds_type` (loki /
            victorialogs → `log_patterns`, prometheus → `metric_trends`). Other
            sources must specify explicitly.
        time_range:
          type: object
          description: >-
            Diagnostic window in Unix seconds. Defaults to the last 15 minutes
            when missing or invalid; windows wider than 6 hours are rejected.
          properties:
            start:
              type: integer
              format: int64
              description: Window start, Unix seconds.
            end:
              type: integer
              format: int64
              description: Window end, Unix seconds.
        methods:
          type: array
          description: >-
            Diagnostic methods to run. When omitted, `log_patterns` defaults to
            `pattern_snapshot + pattern_compare(previous_window)` and
            `metric_trends` defaults to `single_window_shape +
            window_compare(previous_window)`.
          items:
            type: object
            properties:
              name:
                type: string
                description: >-
                  `log_patterns` supports `pattern_snapshot`, `pattern_compare`.
                  `metric_trends` supports `single_window_shape`,
                  `window_compare`.
              baseline:
                type: string
                enum:
                  - previous_window
                  - same_window_yesterday
                  - same_window_last_week
                description: >-
                  Only meaningful for compare-style methods. Defaults to
                  `previous_window`.
        input:
          type: object
          required:
            - query
          properties:
            query:
              type: string
              description: >-
                Query expression. LogQL / VictoriaLogs query syntax for
                `log_patterns`; PromQL for `metric_trends`.
        options:
          type: object
          description: Execution options, all upper-bounded by monit-edge.
          properties:
            max_logs_scanned:
              type: integer
              description: Per-window log scan cap. Default 10 000, hard max 50 000.
            max_patterns:
              type: integer
              description: Max patterns returned. Default 20, hard max 50.
            examples_per_pattern:
              type: integer
              description: Max redacted examples per pattern. Default 2, hard max 3.
            step_seconds:
              type: integer
              description: '`metric_trends` query_range step. Default 60, range [15, 300].'
            max_series:
              type: integer
              description: '`metric_trends` max series considered. Default 50, hard max 200.'
            topk:
              type: integer
              description: >-
                `metric_trends` max notable series returned. Default 10, hard
                max 50.
            timeout_seconds:
              type: integer
              description: >-
                Edge-side diagnostic timeout in seconds. Default 25, hard max
                30.
    SuccessEnvelope:
      type: object
      description: >-
        Success response envelope. On every 2xx response, `request_id`
        identifies the call (also mirrored in the `Flashcat-Request-Id` header)
        and `data` holds the endpoint-specific payload. Failure responses use a
        different shape — see `ErrorResponse`.
      properties:
        request_id:
          type: string
          description: >-
            Unique ID for this request. Mirrored in the Flashcat-Request-Id
            response header. Include it when reporting issues.
          example: 01HK8XQE3Z7JM2NTFQ5YJ8P9R4
        data:
          description: Endpoint-specific payload. See each operation's 200 response schema.
      required:
        - request_id
        - data
    DiagnoseResponse:
      type: object
      description: >-
        Operation-specific diagnostic result. Inspect `operation` first, then
        `results[]`. The shape of `results[].patterns` (for `log_patterns`) vs
        `results[].series` (for `metric_trends`) differs by operation; the full
        schema is documented in the monit-webapi diagnose-api guide.
      properties:
        operation:
          type: string
          enum:
            - log_patterns
            - metric_trends
        ds_type:
          type: string
        ds_name:
          type: string
        query:
          type: string
          description: Query string echoed back from the request.
        window:
          type: object
          properties:
            start:
              type: integer
              format: int64
            end:
              type: integer
              format: int64
        results:
          type: array
          description: One entry per `methods[]` in the request, in the same order.
          items:
            type: object
            properties:
              method:
                type: string
                description: >-
                  `pattern_snapshot` / `pattern_compare` for `log_patterns`;
                  `single_window_shape` / `window_compare` for `metric_trends`.
              baseline:
                type: string
                description: Only present for compare-style methods.
              window:
                type: object
                properties:
                  start:
                    type: integer
                    format: int64
                  end:
                    type: integer
                    format: int64
              baseline_window:
                type: object
                description: Only present for compare-style methods.
                properties:
                  start:
                    type: integer
                    format: int64
                  end:
                    type: integer
                    format: int64
              summary:
                type: object
                description: >-
                  Aggregate summary for this method. Shape differs between
                  `log_patterns` (logs_scanned, patterns_total,
                  surging_threshold, …) and `metric_trends` (series_total,
                  data_quality, observations, …).
              patterns:
                type: array
                description: >-
                  `log_patterns` only. Sorted RCA-first; each item carries
                  pattern_hash, template, count, severity, sources, examples,
                  and (for compare) baseline_count / change_ratio / is_new /
                  is_gone.
                items:
                  type: object
              series:
                type: array
                description: >-
                  `metric_trends` only. Notable series with current / baseline /
                  change / notable_period.
                items:
                  type: object
              warnings:
                type: array
                items:
                  type: string
                description: >-
                  Per-method advisory messages (e.g. `examples redacted`,
                  sampling notices).
    ErrorResponse:
      type: object
      description: Response envelope for errors. `error` is required; `data` is absent.
      properties:
        request_id:
          type: string
          example: 01HK8XQE3Z7JM2NTFQ5YJ8P9R4
        error:
          $ref: '#/components/schemas/DutyError'
      required:
        - request_id
        - error
    DutyError:
      type: object
      description: >-
        Error payload inside the response envelope. Present only on non-2xx
        responses.
      properties:
        code:
          $ref: '#/components/schemas/ErrorCode'
        message:
          type: string
          description: >-
            Human-readable error message, localized by the caller's
            Accept-Language. May contain field names, IDs, or other context from
            the failing request.
          example: The specified parameter template_id is not valid.
      required:
        - code
        - message
    ErrorCode:
      type: string
      description: >-
        Flashduty error code enum. Every failed API response sets `error.code`
        to one of these stable wire strings. HTTP status is informational — the
        authoritative signal is the enum value.


        | Code | HTTP | Meaning |

        |---|---|---|

        | `OK` | 200 | Reserved — not returned on real errors. |

        | `InvalidParameter` | 400 | A required parameter is missing or failed
        validation. |

        | `BadRequest` | 400 | Generic 400 used when no more specific code fits.
        |

        | `InvalidContentType` | 400 | The `Content-Type` header is not
        `application/json`. |

        | `ResourceNotFound` | 400 | The referenced resource does not exist.
        Note: returned as HTTP 400, not 404 (historical choice). |

        | `NoLicense` | 400 | The feature is license-gated and no active license
        was found. |

        | `ReferenceExist` | 400 | Deletion blocked — other entities still
        reference this resource. |

        | `Unauthorized` | 401 | `app_key` is missing, invalid, or expired. |

        | `BalanceNotEnough` | 402 | Billing-gated operation with insufficient
        account balance. |

        | `AccessDenied` | 403 | Authenticated but lacking the permission
        required for this operation. |

        | `RouteNotFound` | 404 | The request URL path is not a known route. |

        | `MethodNotAllowed` | 405 | The HTTP method is not allowed on this
        otherwise-known path. |

        | `UndonedOrderExist` | 409 | An outstanding billing order blocks this
        new one. Wait and retry. |

        | `RequestLocked` | 423 | Operation temporarily locked due to repeated
        failures. |

        | `EntityTooLarge` | 413 | Request body exceeds the configured max size.
        |

        | `RequestTooFrequently` | 429 | Rate limit hit — API-global,
        per-account, or per-integration. |

        | `RequestVerifyRequired` | 428 | Second-factor verification required
        but not supplied. |

        | `DangerousOperation` | 428 | High-risk operation requires MFA
        verification. |

        | `InternalError` | 500 | Unhandled server-side error. Include
        `request_id` in the bug report. |

        | `ServiceUnavailable` | 503 | A backend dependency is unavailable. Try
        again later. |
      enum:
        - OK
        - InvalidParameter
        - BadRequest
        - InvalidContentType
        - ResourceNotFound
        - NoLicense
        - ReferenceExist
        - Unauthorized
        - BalanceNotEnough
        - AccessDenied
        - RouteNotFound
        - MethodNotAllowed
        - UndonedOrderExist
        - RequestLocked
        - EntityTooLarge
        - RequestTooFrequently
        - RequestVerifyRequired
        - DangerousOperation
        - InternalError
        - ServiceUnavailable
      x-enumDescriptions:
        OK: Reserved — not returned on real errors.
        InvalidParameter: A required parameter is missing or failed validation.
        BadRequest: Generic 400 used when no more specific code fits.
        InvalidContentType: The `Content-Type` header is not `application/json`.
        ResourceNotFound: >-
          The referenced resource does not exist. Note: returned as HTTP 400,
          not 404 (historical choice).
        NoLicense: The feature is license-gated and no active license was found.
        ReferenceExist: Deletion blocked — other entities still reference this resource.
        Unauthorized: '`app_key` is missing, invalid, or expired.'
        BalanceNotEnough: Billing-gated operation with insufficient account balance.
        AccessDenied: Authenticated but lacking the permission required for this operation.
        RouteNotFound: The request URL path is not a known route.
        MethodNotAllowed: The HTTP method is not allowed on this otherwise-known path.
        UndonedOrderExist: An outstanding billing order blocks this new one. Wait and retry.
        RequestLocked: Operation temporarily locked due to repeated failures.
        EntityTooLarge: Request body exceeds the configured max size.
        RequestTooFrequently: Rate limit hit — API-global, per-account, or per-integration.
        RequestVerifyRequired: Second-factor verification required but not supplied.
        DangerousOperation: High-risk operation requires MFA verification.
        InternalError: Unhandled server-side error. Include `request_id` in the bug report.
        ServiceUnavailable: A backend dependency is unavailable. Try again later.
      example: InvalidParameter
  responses:
    BadRequest:
      description: Invalid request — usually a missing or malformed parameter.
      content:
        application/json:
          schema:
            $ref: '#/components/schemas/ErrorResponse'
          examples:
            missingParameter:
              value:
                request_id: 01HK8XQE3Z7JM2NTFQ5YJ8P9R4
                error:
                  code: InvalidParameter
                  message: The specified parameter is not valid.
    Unauthorized:
      description: Missing or invalid app_key.
      content:
        application/json:
          schema:
            $ref: '#/components/schemas/ErrorResponse'
          examples:
            missingAppKey:
              value:
                request_id: 01HK8XQE3Z7JM2NTFQ5YJ8P9R4
                error:
                  code: Unauthorized
                  message: You are unauthorized.
    TooManyRequests:
      description: >-
        Rate limit hit. Either the global API limit, a per-account limit, or a
        per-integration limit.
      content:
        application/json:
          schema:
            $ref: '#/components/schemas/ErrorResponse'
          examples:
            rateLimited:
              value:
                request_id: 01HK8XQE3Z7JM2NTFQ5YJ8P9R4
                error:
                  code: RequestTooFrequently
                  message: Request too frequently.
    ServerError:
      description: Unexpected server-side error. Include the request_id when reporting.
      content:
        application/json:
          schema:
            $ref: '#/components/schemas/ErrorResponse'
          examples:
            internal:
              value:
                request_id: 01HK8XQE3Z7JM2NTFQ5YJ8P9R4
                error:
                  code: InternalError
                  message: >-
                    We encountered an internal error, and it has been reported.
                    Please try again later.
  securitySchemes:
    AppKeyAuth:
      type: apiKey
      in: query
      name: app_key
      description: >-
        App key issued from the Flashduty console under Account → APP Keys.
        Required on every public API call. Keep it secret — it grants the same
        access as the owning account.

````