openapi: 3.1.0
info:
  title: Knotrel HTTP API
  version: 1.3.0
  description: |
    REST API for Knotrel, an in-memory dynamic graph connectivity service.

    Knotrel maintains an undirected simple graph in memory and answers dynamic connectivity
    queries across incremental edge/vertex insertions and deletions.

    For full operational semantics, trust model, and lifecycle details, see
    [http-api.md](http-api.md).

    **Responses not tied to one operation.** Unregistered paths get 404 and registered paths
    with another method get 405 with an `Allow` header; both have an empty body (while
    draining, they get 503 `shutting_down` instead). Every request except `GET`/`HEAD` on
    `/health`, `/ready` and `/metrics` answers 503 `shutting_down` while the server drains, and any request that exceeds
    `KNOTREL_REQUEST_TIMEOUT_MS` gets 503 `request_timeout` (for a state-changing request the
    outcome is then unknown). A connection beyond `KNOTREL_MAX_CONNECTIONS` gets a static 503
    `too_many_connections` before any request is read. The `ErrorCode` schema maps every code
    to its status and routes.

    **Authentication (opt-in, experimental, new in 1.3).** By default (`KNOTREL_AUTH=none`)
    there is no authentication: the `security` alternative `{}` applies, identity headers are
    ignored and no operation answers 401 or 403. With `KNOTREL_AUTH=gateway-identity` every
    request, probes and metrics included, must carry the identity headers of the
    `GatewayIdentity` scheme, set by a trusted gateway; a missing or invalid identity answers
    401 `unauthenticated` and a missing role 403 `forbidden`, before the body is read and before
    admission. Each operation names the role it needs in `x-knotrel-role`. Requests to unregistered paths are
    authenticated (401) before they answer 404. See
    [http-api.md](http-api.md#authentication-opt-in).
security:
  - {}
  - GatewayIdentity: []
servers:
  - url: http://127.0.0.1:8080
    description: Default local server address

paths:
  /health:
    get:
      operationId: get_health
      x-knotrel-role: probe
      summary: Liveness probe
      description: |
        Process liveness probe. Returns HTTP 200 while the server process is functional.
        Never acquires the graph lock and stays 200 during graceful shutdown draining.
      tags:
        - Lifecycle
      responses:
        '200':
          description: Process is alive
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/HealthResponse'
              example:
                status: ok
        '401':
          $ref: '#/components/responses/Unauthenticated'
        '403':
          $ref: '#/components/responses/Forbidden'
        '503':
          $ref: '#/components/responses/RequestTimeout'

  /ready:
    get:
      operationId: get_ready
      x-knotrel-role: probe
      summary: Readiness probe
      description: |
        Reports whether the server is initialized and accepting graph operations.
        Does not acquire the graph lock or an admission permit. Always returns
        `Cache-Control: no-store`.
      tags:
        - Lifecycle
      responses:
        '200':
          description: Server is initialized and accepting graph work
          headers:
            Cache-Control:
              schema:
                type: string
                example: no-store
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ReadinessReadyResponse'
              example:
                status: ready
        '401':
          $ref: '#/components/responses/Unauthenticated'
        '403':
          $ref: '#/components/responses/Forbidden'
        '503':
          description: |
            Server is not ready: starting up, draining for shutdown or graph worker failed
            (both modes); in source-managed mode also uninitialized, loading, catching up,
            stale (expired feeder lease) or desynchronized. A probe that exceeded
            `KNOTREL_REQUEST_TIMEOUT_MS` would instead get an `ErrorOutcome` with
            `request_timeout`; the probe takes no lock, so this does not happen in practice.
          headers:
            Cache-Control:
              schema:
                type: string
                example: no-store
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ReadinessNotReadyResponse'
              examples:
                starting:
                  summary: Starting up
                  value:
                    status: starting
                draining:
                  summary: Graceful shutdown in progress
                  value:
                    status: draining
                unavailable:
                  summary: Graph worker failed or panicked
                  value:
                    status: unavailable
                catching_up:
                  summary: Source-managed mode, published image not yet verified by a barrier
                  value:
                    status: catching_up

  /metrics:
    get:
      operationId: get_metrics
      x-knotrel-role: metrics
      summary: Prometheus metrics (opt-in)
      description: |
        Present only when the server is started with `KNOTREL_METRICS_ENABLED=true`;
        otherwise the route is not registered and returns 404. Unauthenticated, like
        every other route. Prometheus text format 0.0.4. Takes no graph lock and no
        admission or import permit. While draining it is still served, with
        `Connection: close`. See observability-contract.md for metric semantics.
      tags:
        - Lifecycle
      responses:
        '200':
          description: Current metrics
          headers:
            Cache-Control:
              schema:
                type: string
                const: no-store
          content:
            text/plain; version=0.0.4; charset=utf-8:
              schema:
                type: string
        '401':
          $ref: '#/components/responses/Unauthenticated'
        '403':
          $ref: '#/components/responses/Forbidden'
        '404':
          description: Metrics are disabled
        '500':
          description: The exposition could not be encoded; empty body.
        '503':
          $ref: '#/components/responses/RequestTimeout'

  /v1/info:
    get:
      operationId: get_info
      x-knotrel-role: read
      summary: Server configuration and metadata
      description: |
        Returns effective immutable configuration settings and engine selection.
        Does not acquire the graph lock or an admission permit.
      tags:
        - Metadata
      responses:
        '200':
          description: Effective server configuration
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ServerInfo'
              example:
                engine: compact-bfs
                experimental: false
                max_pending_jobs: 32
                max_body_bytes: 1048576
                max_batch_operations: 1024
                max_nodes: 100000
                max_edges: 500000
        '401':
          $ref: '#/components/responses/Unauthenticated'
        '403':
          $ref: '#/components/responses/Forbidden'
        '503':
          $ref: '#/components/responses/DrainingOrTimeout'

  /v1/stats:
    get:
      operationId: get_stats
      x-knotrel-role: read
      summary: Live graph state snapshot
      description: |
        Returns a coherent snapshot of the live graph's node and edge counts,
        configured capacity bounds, remaining capacity, and state revision.
        Acquires the graph lock on a blocking worker and shares the bounded admission queue.
        Always returns `Cache-Control: no-store`.
      tags:
        - Metadata
      responses:
        '200':
          description: Coherent graph snapshot; version headers are captured under the same lock
          headers:
            Cache-Control:
              schema:
                type: string
                example: no-store
            ETag:
              $ref: '#/components/headers/ETag'
            X-Knotrel-Instance-Id:
              $ref: '#/components/headers/X-Knotrel-Instance-Id'
            X-Knotrel-Graph-Id:
              $ref: '#/components/headers/X-Knotrel-Graph-Id'
            X-Knotrel-Generation:
              $ref: '#/components/headers/X-Knotrel-Generation'
            X-Knotrel-State-Version:
              $ref: '#/components/headers/X-Knotrel-State-Version'
            X-Knotrel-Source-Position:
              $ref: '#/components/headers/X-Knotrel-Source-Position'
            X-Knotrel-Sync-Status:
              $ref: '#/components/headers/X-Knotrel-Sync-Status'
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/GraphSnapshot'
              example:
                node_count: 42000
                edge_count: 68000
                max_nodes: 100000
                max_edges: 500000
                remaining_nodes: 58000
                remaining_edges: 432000
                state_version: "157"
        '401':
          $ref: '#/components/responses/Unauthenticated'
        '403':
          $ref: '#/components/responses/Forbidden'
        '503':
          description: |
            Request capacity exhausted (`busy`), graph worker unavailable (`unavailable`), server
            draining (`shutting_down`) or request timed out (`request_timeout`). No version headers.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorOutcome'
              examples:
                busy:
                  summary: Queue saturated
                  value:
                    result: error
                    code: busy
                    message: "request capacity exhausted; retry later"
                unavailable:
                  summary: Worker unavailable
                  value:
                    result: error
                    code: unavailable
                    message: "graph worker unavailable"

  /v1/operations:
    post:
      operationId: execute_operation
      x-knotrel-role: read, plus mutate for a non-query operation
      summary: Execute a single graph operation
      description: |
        Executes a single graph mutation (`add_node`, `link`, `cut`) or query (`connected`)
        under exclusive graph lock. Request body must be valid JSON within 1 MiB.
        With `KNOTREL_TOPOLOGY_LIFECYCLE=true`, the lifecycle mutations `set_node_active`,
        `set_edge_enabled` and `remove_node` and the queries `node_state` and `edge_state`
        are also executed; without it they always parse but are rejected with 409
        `topology_lifecycle_disabled` before execution.
        With the experimental `KNOTREL_MAX_CONCURRENT_QUERIES` set, an admitted query may first
        wait until fewer than that many all-query requests are running; the wait counts toward
        the request timeout, and responses, status codes and admission are unchanged.
      tags:
        - Operations
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/Operation'
            examples:
              add_node:
                summary: Add isolated vertex
                value:
                  op: add_node
                  node: "1"
              link:
                summary: Insert undirected edge
                value:
                  op: link
                  source: "1"
                  target: "2"
              cut:
                summary: Remove undirected edge
                value:
                  op: cut
                  source: "1"
                  target: "2"
              connected:
                summary: Query connectivity
                value:
                  op: connected
                  source: "1"
                  target: "2"
              set_node_active:
                summary: Set a node flag (lifecycle support only)
                value:
                  op: set_node_active
                  node: "2"
                  active: false
              set_edge_enabled:
                summary: Set an edge flag (lifecycle support only)
                value:
                  op: set_edge_enabled
                  source: "1"
                  target: "2"
                  enabled: false
              remove_node:
                summary: Remove a node and its incident edges (lifecycle support only)
                value:
                  op: remove_node
                  node: "2"
              node_state:
                summary: Query a node's registration and flag (lifecycle support only)
                value:
                  op: node_state
                  node: "2"
              edge_state:
                summary: Query an edge's registration and flags (lifecycle support only)
                value:
                  op: edge_state
                  source: "1"
                  target: "2"
      responses:
        '200':
          description: |
            Operation completed successfully. Version headers are captured under the same lock
            acquisition as the outcome. Every response of an executed operation carries them,
            also 404, 422 and the source-managed 503 (`uninitialized`, `loading`,
            `desynchronized`); refusals before execution (400, 409, 413, 415 and 503 `busy`,
            `unavailable`, `shutting_down`, `request_timeout`) carry none.
          headers:
            ETag:
              $ref: '#/components/headers/ETag'
            X-Knotrel-Instance-Id:
              $ref: '#/components/headers/X-Knotrel-Instance-Id'
            X-Knotrel-Graph-Id:
              $ref: '#/components/headers/X-Knotrel-Graph-Id'
            X-Knotrel-Generation:
              $ref: '#/components/headers/X-Knotrel-Generation'
            X-Knotrel-State-Version:
              $ref: '#/components/headers/X-Knotrel-State-Version'
            X-Knotrel-Source-Position:
              $ref: '#/components/headers/X-Knotrel-Source-Position'
            X-Knotrel-Sync-Status:
              $ref: '#/components/headers/X-Knotrel-Sync-Status'
          content:
            application/json:
              schema:
                oneOf:
                  - $ref: '#/components/schemas/ChangedOutcome'
                  - $ref: '#/components/schemas/ConnectedOutcome'
                  - $ref: '#/components/schemas/NodeStateOutcome'
                  - $ref: '#/components/schemas/EdgeStateOutcome'
              examples:
                mutation_changed:
                  summary: Mutation applied (topology changed)
                  value:
                    result: changed
                    changed: true
                mutation_noop:
                  summary: Mutation applied as no-op (no change)
                  value:
                    result: changed
                    changed: false
                query_connected:
                  summary: Vertices are connected
                  value:
                    result: connected
                    connected: true
                query_disconnected:
                  summary: Vertices are disconnected
                  value:
                    result: connected
                    connected: false
                node_state:
                  summary: Registered inactive node
                  value:
                    result: node_state
                    registered: true
                    active: false
                edge_state:
                  summary: Registered enabled edge that is not effective
                  value:
                    result: edge_state
                    registered: true
                    enabled: true
                    effective: false
        '400':
          description: Malformed JSON syntax, or a body that could not be read before its end (client abort, malformed
            chunked encoding; `invalid_request`, "request body could not be read"). Never a 413.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorOutcome'
              example:
                result: error
                code: invalid_request
                message: "request body is not valid JSON"
        '401':
          $ref: '#/components/responses/Unauthenticated'
        '403':
          $ref: '#/components/responses/Forbidden'
        '404':
          description: |
            Unknown query vertex, or unknown node of `set_node_active` / `set_edge_enabled`
            (`unknown_node`); unregistered edge of `set_edge_enabled` (`unknown_edge`). Carries
            the version headers.
          headers:
            ETag:
              $ref: '#/components/headers/ETag'
            X-Knotrel-Instance-Id:
              $ref: '#/components/headers/X-Knotrel-Instance-Id'
            X-Knotrel-Graph-Id:
              $ref: '#/components/headers/X-Knotrel-Graph-Id'
            X-Knotrel-Generation:
              $ref: '#/components/headers/X-Knotrel-Generation'
            X-Knotrel-State-Version:
              $ref: '#/components/headers/X-Knotrel-State-Version'
            X-Knotrel-Source-Position:
              $ref: '#/components/headers/X-Knotrel-Source-Position'
            X-Knotrel-Sync-Status:
              $ref: '#/components/headers/X-Knotrel-Sync-Status'
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorOutcome'
              examples:
                unknown_node:
                  summary: Unknown vertex
                  value:
                    result: error
                    code: unknown_node
                    message: "unknown node: 3"
                unknown_edge:
                  summary: Edge not registered (lifecycle support only)
                  value:
                    result: error
                    code: unknown_edge
                    message: "unknown edge: 1-3"
        '409':
          description: |
            Mutation sent in source-managed mode (`direct_mutation_disabled`), or lifecycle
            operation while lifecycle support is off (`topology_lifecycle_disabled`).
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorOutcome'
              examples:
                direct_mutation_disabled:
                  summary: Source-managed mode
                  value:
                    result: error
                    code: direct_mutation_disabled
                    message: "direct graph mutations are disabled in source-managed mode; use feeder endpoints"
                topology_lifecycle_disabled:
                  summary: Lifecycle support is off
                  value:
                    result: error
                    code: topology_lifecycle_disabled
                    message: "node and edge lifecycle support is disabled; set KNOTREL_TOPOLOGY_LIFECYCLE=true (requires KNOTREL_ENGINE=compact-bfs or cluster-forest)"
        '413':
          description: Request body exceeds the 1 MiB limit (`invalid_request`); only the limit answers 413.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorOutcome'
              example:
                result: error
                code: invalid_request
                message: "request body exceeded 1048576 bytes"
        '415':
          description: Missing or unsupported JSON Content-Type
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorOutcome'
              example:
                result: error
                code: invalid_request
                message: "Expected request with `Content-Type: application/json`"
        '422':
          description: |
            Invalid request shape (`invalid_request`, no version headers), self-loop (`self_loop`)
            or capacity limit exceeded (`node_limit_exceeded`, `edge_limit_exceeded`); the domain
            errors carry the version headers.
          headers:
            ETag:
              $ref: '#/components/headers/ETag'
            X-Knotrel-Instance-Id:
              $ref: '#/components/headers/X-Knotrel-Instance-Id'
            X-Knotrel-Graph-Id:
              $ref: '#/components/headers/X-Knotrel-Graph-Id'
            X-Knotrel-Generation:
              $ref: '#/components/headers/X-Knotrel-Generation'
            X-Knotrel-State-Version:
              $ref: '#/components/headers/X-Knotrel-State-Version'
            X-Knotrel-Source-Position:
              $ref: '#/components/headers/X-Knotrel-Source-Position'
            X-Knotrel-Sync-Status:
              $ref: '#/components/headers/X-Knotrel-Sync-Status'
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorOutcome'
              examples:
                shape:
                  summary: Missing required field or invalid format
                  value:
                    result: error
                    code: invalid_request
                    message: "missing field `op`"
                self_loop:
                  summary: Self-loop not permitted
                  value:
                    result: error
                    code: self_loop
                    message: "self-loops are not allowed"
                node_limit:
                  summary: Node capacity ceiling exceeded
                  value:
                    result: error
                    code: node_limit_exceeded
                    message: "node capacity limit exceeded"
                edge_limit:
                  summary: Edge capacity ceiling exceeded
                  value:
                    result: error
                    code: edge_limit_exceeded
                    message: "edge capacity limit exceeded"
        '503':
          description: |
            Server busy (`busy`), graph worker unavailable (`unavailable`), draining
            (`shutting_down`) or request timed out (`request_timeout`; the effect of a mutation is
            then unknown). In source-managed mode a query is also refused while the graph has no
            usable generation: `uninitialized` (no baseline), `loading` (baseline import running) or
            `desynchronized` (rebuild required); these three carry the version headers.
          headers:
            ETag:
              $ref: '#/components/headers/ETag'
            X-Knotrel-Instance-Id:
              $ref: '#/components/headers/X-Knotrel-Instance-Id'
            X-Knotrel-Graph-Id:
              $ref: '#/components/headers/X-Knotrel-Graph-Id'
            X-Knotrel-Generation:
              $ref: '#/components/headers/X-Knotrel-Generation'
            X-Knotrel-State-Version:
              $ref: '#/components/headers/X-Knotrel-State-Version'
            X-Knotrel-Source-Position:
              $ref: '#/components/headers/X-Knotrel-Source-Position'
            X-Knotrel-Sync-Status:
              $ref: '#/components/headers/X-Knotrel-Sync-Status'
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorOutcome'
              examples:
                busy:
                  summary: Job queue capacity exhausted
                  value:
                    result: error
                    code: busy
                    message: "request capacity exhausted; retry later"
                unavailable:
                  summary: Graph worker failed or panicked
                  value:
                    result: error
                    code: unavailable
                    message: "graph worker unavailable"
                shutting_down:
                  summary: Server is draining
                  value:
                    result: error
                    code: shutting_down
                    message: "server is shutting down; retry against another instance"
                uninitialized:
                  summary: Source-managed mode, no baseline imported yet
                  value:
                    result: error
                    code: uninitialized
                    message: "graph is uninitialized; baseline import required"

  /v1/batch:
    post:
      operationId: execute_batch
      x-knotrel-role: read, plus mutate if any operation is not a query
      summary: Execute an ordered batch of graph operations
      description: |
        Executes between 1 and 1024 operations under a single graph lock acquisition.
        Results correspond one-to-one with the input operations.
        Batches do not provide rollback: subsequent failures do not revert earlier operations.
        Version headers on a 200 response are captured under the same lock acquisition and
        describe the state after the whole batch. Error responses carry no version headers.
        In source-managed mode, a batch containing any mutation is rejected with 409 before
        the batch size is checked. Without lifecycle support, a batch containing any
        lifecycle operation is rejected with 409 `topology_lifecycle_disabled` before the
        mode and size checks.
        In source-managed mode, while the graph is uninitialized, loading or desynchronized, an
        all-query batch is answered 200 with one error outcome per operation (`uninitialized`,
        `loading` or `desynchronized`) and the version headers; nothing was executed.
        With the experimental `KNOTREL_MAX_CONCURRENT_QUERIES` set, an admitted all-query batch
        may first wait until fewer than that many all-query requests are running; the wait counts
        toward the request timeout, and responses, status codes and admission are unchanged.
      tags:
        - Operations
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/BatchRequest'
            example:
              operations:
                - op: link
                  source: "1"
                  target: "2"
                - op: connected
                  source: "1"
                  target: "2"
                - op: cut
                  source: "1"
                  target: "2"
      responses:
        '200':
          description: Batch executed; per-operation outcomes returned in order
          headers:
            ETag:
              $ref: '#/components/headers/ETag'
            X-Knotrel-Instance-Id:
              $ref: '#/components/headers/X-Knotrel-Instance-Id'
            X-Knotrel-Graph-Id:
              $ref: '#/components/headers/X-Knotrel-Graph-Id'
            X-Knotrel-Generation:
              $ref: '#/components/headers/X-Knotrel-Generation'
            X-Knotrel-State-Version:
              $ref: '#/components/headers/X-Knotrel-State-Version'
            X-Knotrel-Source-Position:
              $ref: '#/components/headers/X-Knotrel-Source-Position'
            X-Knotrel-Sync-Status:
              $ref: '#/components/headers/X-Knotrel-Sync-Status'
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/BatchResponse'
              example:
                results:
                  - result: changed
                    changed: true
                  - result: connected
                    connected: true
                  - result: changed
                    changed: true
        '400':
          description: Malformed JSON syntax, or a body that could not be read before its end (client abort, malformed
            chunked encoding; `invalid_request`, "request body could not be read"). Never a 413.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorOutcome'
              example:
                result: error
                code: invalid_request
                message: "request body is not valid JSON"
        '401':
          $ref: '#/components/responses/Unauthenticated'
        '403':
          $ref: '#/components/responses/Forbidden'
        '413':
          description: Request body exceeds the 1 MiB limit (`invalid_request`); only the limit answers 413.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorOutcome'
              example:
                result: error
                code: invalid_request
                message: "request body exceeded 1048576 bytes"
        '415':
          description: Missing or unsupported JSON Content-Type
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorOutcome'
              example:
                result: error
                code: invalid_request
                message: "Expected request with `Content-Type: application/json`"
        '409':
          description: |
            Source-managed mode and the batch contains a mutation (`direct_mutation_disabled`),
            or lifecycle support is off and the batch contains a lifecycle operation
            (`topology_lifecycle_disabled`).
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorOutcome'
              examples:
                direct_mutation_disabled:
                  summary: Source-managed mode
                  value:
                    result: error
                    code: direct_mutation_disabled
                    message: "direct graph mutations are disabled in source-managed mode; use feeder endpoints"
                topology_lifecycle_disabled:
                  summary: Lifecycle support is off
                  value:
                    result: error
                    code: topology_lifecycle_disabled
                    message: "node and edge lifecycle support is disabled; set KNOTREL_TOPOLOGY_LIFECYCLE=true (requires KNOTREL_ENGINE=compact-bfs or cluster-forest)"
        '422':
          description: Invalid batch size (not 1–1024) or invalid operation shape in batch
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorOutcome'
              examples:
                batch_size:
                  summary: Batch size outside 1–1024
                  value:
                    result: error
                    code: invalid_batch_size
                    message: "batches must contain 1 to 1024 operations"
                shape:
                  summary: Invalid field or ID format in operation
                  value:
                    result: error
                    code: invalid_request
                    message: "node IDs must be nonempty strings of ASCII decimal digits"
        '503':
          description: |
            Server busy, unavailable, shutting down, or request timed out. After
            `request_timeout`, the effect of the batch is unknown: an admitted worker
            may still apply it later.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorOutcome'
              examples:
                busy:
                  summary: No graph job slot available; no operation was admitted
                  value:
                    result: error
                    code: busy
                    message: "request capacity exhausted; retry later"
                unavailable:
                  summary: Graph worker unavailable
                  value:
                    result: error
                    code: unavailable
                    message: "graph worker unavailable"
                shutting_down:
                  summary: Server is draining
                  value:
                    result: error
                    code: shutting_down
                    message: "server is shutting down; retry against another instance"
                request_timeout:
                  summary: Request time limit exceeded; effect unknown
                  value:
                    result: error
                    code: request_timeout
                    message: "request exceeded the server time limit; its effect is unknown"

  /v1/feeder/session:
    post:
      operationId: feeder_session
      x-knotrel-role: feeder-control
      summary: Acquire or supersede a feeder session
      tags:
      - Feeder
      description: "Register a monotonic feeder epoch with a lease of 1000\u201360000 ms. Session ownership does not\
        \ itself publish a graph or establish readiness. Available only in source_managed mode. Both the header and\
        \ body instance_id must match the serving process. This is fencing, not authentication. Except for import,\
        \ request bodies have a fixed 1 MiB limit. See http-api.md and integration-contract.md for validation order\
        \ and recovery semantics."
      parameters:
      - name: X-Knotrel-Instance-Id
        in: header
        required: true
        description: Current process instance ID from GET /v1/info.
        schema:
          type: string
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/SessionRequest'
      responses:
        '200':
          description: Successful feeder operation.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/SessionResponse'
        '400':
          description: Malformed JSON or a body that could not be read before its end (client abort, malformed chunked
            encoding; `invalid_request`), missing or invalid `X-Knotrel-Instance-Id` (`invalid_instance_id`) or
            `lease_duration_ms` outside 1000–60000 (`invalid_lease_duration`; checked by the server, not as a 422).
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorOutcome'
        '401':
          $ref: '#/components/responses/Unauthenticated'
        '403':
          $ref: '#/components/responses/Forbidden'
        '409':
          description: >-
            `mode_conflict` (standalone mode), `stale_instance_id`, `fenced_feeder_session` (an older epoch than the
            registered one).
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorOutcome'
        '413':
          description: Request body exceeds 1 MiB (`invalid_request`); only the limit answers 413, an unreadable body
            answers 400.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorOutcome'
        '415':
          description: Content-Type is not application/json.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorOutcome'
        '422':
          description: Invalid payload shape (`invalid_request`).
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorOutcome'
        '503':
          description: The feeder control lane (session and heartbeat, 2 permits) is exhausted (`busy`), the graph
            worker is unavailable (`unavailable`), the server is draining (`shutting_down`) or the request timed out
            (`request_timeout`; a dispatched worker may still complete, so the outcome is uncertain). `busy` means
            nothing of the request was applied; retry later. This route never answers `import_in_progress`.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorOutcome'
  /v1/feeder/heartbeat:
    post:
      operationId: feeder_heartbeat
      x-knotrel-role: feeder-control
      summary: Renew the current feeder lease
      tags:
      - Feeder
      description: Renews the matching session lease. A heartbeat does not restore ready after lease expiry; recovery
        requires a new epoch and a verified barrier. Available only in source_managed mode. Both the header and body
        instance_id must match the serving process. This is fencing, not authentication. Except for import, request
        bodies have a fixed 1 MiB limit. See http-api.md and integration-contract.md for validation order and recovery
        semantics.
      parameters:
      - name: X-Knotrel-Instance-Id
        in: header
        required: true
        description: Current process instance ID from GET /v1/info.
        schema:
          type: string
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/HeartbeatRequest'
      responses:
        '200':
          description: Successful feeder operation.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/HeartbeatResponse'
        '400':
          description: Malformed JSON (`invalid_request`) or missing or invalid `X-Knotrel-Instance-Id` (`invalid_instance_id`).
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorOutcome'
        '401':
          $ref: '#/components/responses/Unauthenticated'
        '403':
          $ref: '#/components/responses/Forbidden'
        '409':
          description: >-
            `mode_conflict`, `stale_instance_id`, `session_required`, `fenced_feeder_session`.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorOutcome'
        '413':
          description: Request body exceeds 1 MiB (`invalid_request`); only the limit answers 413, an unreadable body
            answers 400.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorOutcome'
        '415':
          description: Content-Type is not application/json.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorOutcome'
        '422':
          description: Invalid payload shape (`invalid_request`).
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorOutcome'
        '503':
          description: The feeder control lane (session and heartbeat, 2 permits) is exhausted (`busy`), the graph
            worker is unavailable (`unavailable`), the server is draining (`shutting_down`) or the request timed out
            (`request_timeout`; a dispatched worker may still complete, so the outcome is uncertain). `busy` means
            nothing of the request was applied; retry later. This route never answers `import_in_progress`.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorOutcome'
  /v1/feeder/import:
    post:
      operationId: feeder_import
      x-knotrel-role: import
      summary: Publish a complete graph atomically
      tags:
      - Feeder
      description: Builds a candidate before atomic publication. create_only requires generation 0; replace requires
        an exact composite If-Match token from GET /v1/stats. Successful publication advances generation, resets local
        revision and delivery sequence, and enters catching_up. One import permit is acquired before body consumption;
        the configurable KNOTREL_MAX_IMPORT_BODY_BYTES limit defaults to 64 MiB. Conflicting repeated node/edge flags
        are rejected. A timeout after worker dispatch can leave publication uncertain; reconcile before retrying.
        Available only in source_managed mode. Both the header and body instance_id must match the serving process.
        This is fencing, not authentication. Except for import, request bodies have a fixed 1 MiB limit. See http-api.md
        and integration-contract.md for validation order and recovery semantics.
      parameters:
      - name: X-Knotrel-Instance-Id
        in: header
        required: true
        description: Current process instance ID from GET /v1/info.
        schema:
          type: string
      - name: If-Match
        in: header
        required: false
        description: Required for mode=replace; one exact quoted composite ETag from /v1/stats. Missing or mismatching
          replacement preconditions return 412.
        schema:
          type: string
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/ImportRequest'
      responses:
        '201':
          description: Published graph.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ImportResponse'
          headers:
            ETag:
              $ref: '#/components/headers/ETag'
            X-Knotrel-Instance-Id:
              $ref: '#/components/headers/X-Knotrel-Instance-Id'
            X-Knotrel-Graph-Id:
              $ref: '#/components/headers/X-Knotrel-Graph-Id'
            X-Knotrel-Generation:
              $ref: '#/components/headers/X-Knotrel-Generation'
            X-Knotrel-State-Version:
              $ref: '#/components/headers/X-Knotrel-State-Version'
            X-Knotrel-Source-Position:
              $ref: '#/components/headers/X-Knotrel-Source-Position'
            X-Knotrel-Sync-Status:
              $ref: '#/components/headers/X-Knotrel-Sync-Status'
        '400':
          description: Malformed JSON or a body that could not be read before its end (client abort, malformed chunked
            encoding; `invalid_request`), missing or invalid `X-Knotrel-Instance-Id` (`invalid_instance_id`) or
            `graph_id` other than `default` (`invalid_graph_id`).
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorOutcome'
        '401':
          $ref: '#/components/responses/Unauthenticated'
        '403':
          $ref: '#/components/responses/Forbidden'
        '409':
          description: >-
            `mode_conflict`, `stale_instance_id`, `session_required`, `fenced_feeder_session`, `lease_expired`,
            `graph_already_initialized` (`create_only` on an initialized graph), `generation_exhausted`,
            `topology_lifecycle_disabled` (lifecycle flags without lifecycle support).
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorOutcome'
        '413':
          description: Body exceeds `KNOTREL_MAX_IMPORT_BODY_BYTES` (`payload_too_large`, unlike the 1 MiB limit of
            the other routes, which answers `invalid_request`), either by its declared `Content-Length` (refused before
            any body byte is read) or while it is received, chunked bodies included. Only the limit answers 413; a body
            that could not be read for another reason answers 400 `invalid_request`.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorOutcome'
        '415':
          description: Content-Type is not application/json.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorOutcome'
        '422':
          description: Invalid payload shape, IDs or bounds (`invalid_request`), or a topology the graph refuses
            (`self_loop`, `node_limit_exceeded`, `edge_limit_exceeded`, `invalid_node`, `invalid_edge`).
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorOutcome'
        '503':
          description: Another import holds the single import permit (`import_in_progress`, answered before the
            body is read), the graph worker is unavailable (`unavailable`), the server is draining (`shutting_down`)
            or the request timed out (`request_timeout`; a dispatched worker may still complete, so the outcome is
            uncertain). Imports use no feeder admission lane and never answer `busy`.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorOutcome'
        '412':
          description: Missing or mismatching replacement precondition.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorOutcome'
  /v1/feeder/events:
    post:
      operationId: feeder_events
      x-knotrel-role: feeder-data
      summary: Apply ordered source events
      tags:
      - Feeder
      description: "Accepts 1\u20131024 events, with source continuity, generation/session fencing and bounded duplicate\
        \ verification. Multi-event execution stops at the first error and preserves the applied prefix; no rollback.\
        \ The source position never advances ahead of applied events. Exact single-event retries can return duplicate;\
        \ retained matching duplicates in batches are skipped and events_applied counts only newly applied events.\
        \ Whole-request validation failures apply no events. Timeouts can leave the applied prefix uncertain. This\
        \ differs from the legacy /v1/batch continue-on-error contract. Available only in source_managed mode. Both\
        \ the header and body instance_id must match the serving process. This is fencing, not authentication. Except\
        \ for import, request bodies have a fixed 1 MiB limit. See http-api.md and integration-contract.md for validation\
        \ order and recovery semantics."
      parameters:
      - name: X-Knotrel-Instance-Id
        in: header
        required: true
        description: Current process instance ID from GET /v1/info.
        schema:
          type: string
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/FeederEventsRequest'
      responses:
        '200':
          description: Successful feeder operation.
          content:
            application/json:
              schema:
                oneOf:
                - $ref: '#/components/schemas/FeederEventsResponse'
                - $ref: '#/components/schemas/FeederDuplicateResponse'
          headers:
            ETag:
              $ref: '#/components/headers/ETag'
            X-Knotrel-Instance-Id:
              $ref: '#/components/headers/X-Knotrel-Instance-Id'
            X-Knotrel-Graph-Id:
              $ref: '#/components/headers/X-Knotrel-Graph-Id'
            X-Knotrel-Generation:
              $ref: '#/components/headers/X-Knotrel-Generation'
            X-Knotrel-State-Version:
              $ref: '#/components/headers/X-Knotrel-State-Version'
            X-Knotrel-Source-Position:
              $ref: '#/components/headers/X-Knotrel-Source-Position'
            X-Knotrel-Sync-Status:
              $ref: '#/components/headers/X-Knotrel-Sync-Status'
        '400':
          description: Malformed JSON or a body that could not be read before its end (client abort, malformed chunked
            encoding; `invalid_request`), missing or invalid `X-Knotrel-Instance-Id` (`invalid_instance_id`) or
            `graph_id` other than `default` (`invalid_graph_id`; a 400, although the schema declares `const`).
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorOutcome'
        '401':
          $ref: '#/components/responses/Unauthenticated'
        '403':
          $ref: '#/components/responses/Forbidden'
        '409':
          description: >-
            `mode_conflict`, `stale_instance_id`, `session_required`, `fenced_feeder_session`, `lease_expired`,
            `stale_generation`, `graph_uninitialized`, `graph_desynchronized`, `source_mismatch`,
            `source_epoch_mismatch`, `out_of_order_sequence`, `source_predecessor_mismatch`, `conflicting_duplicate`,
            `unverifiable_duplicate`, `sequence_exhausted`, `topology_lifecycle_disabled`. Partial failures include
            coherent version headers; pre-execution rejections do not necessarily include them.
          content:
            application/json:
              schema:
                oneOf:
                - $ref: '#/components/schemas/ErrorOutcome'
                - $ref: '#/components/schemas/PartialBatchFailure'
          headers:
            ETag:
              $ref: '#/components/headers/ETag'
            X-Knotrel-Instance-Id:
              $ref: '#/components/headers/X-Knotrel-Instance-Id'
            X-Knotrel-Graph-Id:
              $ref: '#/components/headers/X-Knotrel-Graph-Id'
            X-Knotrel-Generation:
              $ref: '#/components/headers/X-Knotrel-Generation'
            X-Knotrel-State-Version:
              $ref: '#/components/headers/X-Knotrel-State-Version'
            X-Knotrel-Source-Position:
              $ref: '#/components/headers/X-Knotrel-Source-Position'
            X-Knotrel-Sync-Status:
              $ref: '#/components/headers/X-Knotrel-Sync-Status'
        '413':
          description: Request body exceeds 1 MiB (`invalid_request`); only the limit answers 413, an unreadable body
            answers 400.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorOutcome'
        '415':
          description: Content-Type is not application/json.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorOutcome'
        '422':
          description: >-
            Invalid payload shape, operands or bounds (`invalid_request`); a single-event domain error
            carries its own code (`self_loop`, `node_limit_exceeded`, `edge_limit_exceeded`, `invalid_node`,
            `invalid_edge`, and with lifecycle support `unknown_node`, `unknown_edge`); a multi-event partial failure
            has `code: event_failed` and the domain code in `error.code`. Partial failures include coherent version
            headers; pre-execution rejections do not necessarily include them.
          content:
            application/json:
              schema:
                oneOf:
                - $ref: '#/components/schemas/ErrorOutcome'
                - $ref: '#/components/schemas/PartialBatchFailure'
          headers:
            ETag:
              $ref: '#/components/headers/ETag'
            X-Knotrel-Instance-Id:
              $ref: '#/components/headers/X-Knotrel-Instance-Id'
            X-Knotrel-Graph-Id:
              $ref: '#/components/headers/X-Knotrel-Graph-Id'
            X-Knotrel-Generation:
              $ref: '#/components/headers/X-Knotrel-Generation'
            X-Knotrel-State-Version:
              $ref: '#/components/headers/X-Knotrel-State-Version'
            X-Knotrel-Source-Position:
              $ref: '#/components/headers/X-Knotrel-Source-Position'
            X-Knotrel-Sync-Status:
              $ref: '#/components/headers/X-Knotrel-Sync-Status'
        '503':
          description: The feeder data lane (events, barrier and gap, `KNOTREL_FEEDER_RESERVED_JOBS` permits) is
            exhausted (`busy`), the graph worker is unavailable (`unavailable`), the server is draining
            (`shutting_down`) or the request timed out (`request_timeout`; a dispatched worker may still complete, so
            the outcome is uncertain). `busy` means nothing of the request was applied; it may be resubmitted
            unchanged. This route never answers `import_in_progress`.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorOutcome'
  /v1/feeder/gap:
    post:
      operationId: feeder_gap
      x-knotrel-role: feeder-control
      summary: Declare an unrecoverable source gap
      tags:
      - Feeder
      description: Marks the published graph desynchronized without advancing the applied source frontier. Retains
        topology for diagnostics; an atomic replacement import is required for recovery. Available only in source_managed
        mode. Both the header and body instance_id must match the serving process. This is fencing, not authentication.
        Except for import, request bodies have a fixed 1 MiB limit. See http-api.md and integration-contract.md for
        validation order and recovery semantics.
      parameters:
      - name: X-Knotrel-Instance-Id
        in: header
        required: true
        description: Current process instance ID from GET /v1/info.
        schema:
          type: string
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/GapRequest'
      responses:
        '200':
          description: Successful feeder operation.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/GapResponse'
          headers:
            ETag:
              $ref: '#/components/headers/ETag'
            X-Knotrel-Instance-Id:
              $ref: '#/components/headers/X-Knotrel-Instance-Id'
            X-Knotrel-Graph-Id:
              $ref: '#/components/headers/X-Knotrel-Graph-Id'
            X-Knotrel-Generation:
              $ref: '#/components/headers/X-Knotrel-Generation'
            X-Knotrel-State-Version:
              $ref: '#/components/headers/X-Knotrel-State-Version'
            X-Knotrel-Source-Position:
              $ref: '#/components/headers/X-Knotrel-Source-Position'
            X-Knotrel-Sync-Status:
              $ref: '#/components/headers/X-Knotrel-Sync-Status'
        '400':
          description: Malformed JSON or a body that could not be read before its end (client abort, malformed chunked
            encoding; `invalid_request`), missing or invalid `X-Knotrel-Instance-Id` (`invalid_instance_id`) or
            `graph_id` other than `default` (`invalid_graph_id`; a 400, although the schema declares `const`).
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorOutcome'
        '401':
          $ref: '#/components/responses/Unauthenticated'
        '403':
          $ref: '#/components/responses/Forbidden'
        '409':
          description: >-
            `mode_conflict`, `stale_instance_id`, `session_required`, `fenced_feeder_session`, `lease_expired`,
            `stale_generation`, `graph_uninitialized`.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorOutcome'
        '413':
          description: Request body exceeds 1 MiB (`invalid_request`); only the limit answers 413, an unreadable body
            answers 400.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorOutcome'
        '415':
          description: Content-Type is not application/json.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorOutcome'
        '422':
          description: Invalid payload shape or bounds (`invalid_request`).
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorOutcome'
        '503':
          description: The feeder data lane (events, barrier and gap, `KNOTREL_FEEDER_RESERVED_JOBS` permits) is
            exhausted (`busy`), the graph worker is unavailable (`unavailable`), the server is draining
            (`shutting_down`) or the request timed out (`request_timeout`; a dispatched worker may still complete, so
            the outcome is uncertain). `busy` means nothing of the request was applied; it may be resubmitted
            unchanged. This route never answers `import_in_progress`.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorOutcome'
  /v1/feeder/barrier:
    post:
      operationId: feeder_barrier
      x-knotrel-role: feeder-control
      summary: Verify synchronization completion
      tags:
      - Feeder
      description: 'Verification-only: does not advance the source frontier. The delivery sequence must equal the
        applied sequence; if supplied, the source position must match exactly. A valid barrier promotes catching_up/stale
        to ready or acknowledges already_synchronized. An expired epoch cannot restore readiness; a newly registered
        epoch is required. Available only in source_managed mode. Both the header and body instance_id must match
        the serving process. This is fencing, not authentication. Except for import, request bodies have a fixed 1
        MiB limit. See http-api.md and integration-contract.md for validation order and recovery semantics.'
      parameters:
      - name: X-Knotrel-Instance-Id
        in: header
        required: true
        description: Current process instance ID from GET /v1/info.
        schema:
          type: string
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/BarrierRequest'
      responses:
        '200':
          description: Successful feeder operation.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/BarrierResponse'
          headers:
            ETag:
              $ref: '#/components/headers/ETag'
            X-Knotrel-Instance-Id:
              $ref: '#/components/headers/X-Knotrel-Instance-Id'
            X-Knotrel-Graph-Id:
              $ref: '#/components/headers/X-Knotrel-Graph-Id'
            X-Knotrel-Generation:
              $ref: '#/components/headers/X-Knotrel-Generation'
            X-Knotrel-State-Version:
              $ref: '#/components/headers/X-Knotrel-State-Version'
            X-Knotrel-Source-Position:
              $ref: '#/components/headers/X-Knotrel-Source-Position'
            X-Knotrel-Sync-Status:
              $ref: '#/components/headers/X-Knotrel-Sync-Status'
        '400':
          description: Malformed JSON or a body that could not be read before its end (client abort, malformed chunked
            encoding; `invalid_request`), missing or invalid `X-Knotrel-Instance-Id` (`invalid_instance_id`) or
            `graph_id` other than `default` (`invalid_graph_id`; a 400, although the schema declares `const`).
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorOutcome'
        '401':
          $ref: '#/components/responses/Unauthenticated'
        '403':
          $ref: '#/components/responses/Forbidden'
        '409':
          description: >-
            `mode_conflict`, `stale_instance_id`, `session_required`, `fenced_feeder_session`, `lease_expired`,
            `stale_generation`, `graph_uninitialized`, `graph_desynchronized`, `barrier_not_reached`,
            `superseded_barrier`, `barrier_position_mismatch`. After a lease expiry, a barrier under
            `feeder_epoch <= last_expired_epoch` gets `fenced_feeder_session` whatever its sequence and position:
            the precedence is failed (503 `unavailable`), session and lease, generation, `graph_uninitialized`,
            `graph_desynchronized`, the recovery fence, the `barrier_source_position` bound (422),
            `barrier_not_reached`, `superseded_barrier`, `barrier_position_mismatch`. Every rejection leaves the
            state unchanged.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorOutcome'
        '413':
          description: Request body exceeds 1 MiB (`invalid_request`); only the limit answers 413, an unreadable body
            answers 400.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorOutcome'
        '415':
          description: Content-Type is not application/json.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorOutcome'
        '422':
          description: Invalid payload shape or bounds (`invalid_request`), including a `barrier_source_position`
            outside 1 to 256 bytes.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorOutcome'
        '503':
          description: The feeder data lane (events, barrier and gap, `KNOTREL_FEEDER_RESERVED_JOBS` permits) is
            exhausted (`busy`), the graph worker is unavailable (`unavailable`), the server is draining
            (`shutting_down`) or the request timed out (`request_timeout`; a dispatched worker may still complete, so
            the outcome is uncertain). `busy` means nothing of the request was applied; it may be resubmitted
            unchanged. This route never answers `import_in_progress`.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorOutcome'

  /v1/nodes:
    get:
      x-knotrel-stability: experimental
      operationId: list_nodes
      x-knotrel-role: inspect
      summary: List nodes in ascending ID order (inspection)
      tags:
        - Inspection
      description: |
        Read-only inspection route, enabled by `KNOTREL_INSPECTION=true` (otherwise 409
        `inspection_disabled`, before admission). Works with every engine. Runs like
        `GET /v1/stats`: bounded admission, blocking worker, shared graph lock, no readiness
        gate, available in both modes. Each page is computed under one lock acquisition and
        carries the version headers of that instant; pages are not a snapshot. A node present
        for the whole traversal is returned exactly once; nodes added or removed meanwhile may
        or may not appear. A page examines at most 10000 nodes, so it may hold fewer than
        `limit` items while `next_after` is non-null. Restart when `X-Knotrel-Instance-Id` or
        `X-Knotrel-Generation` changes between pages.
      parameters:
        - $ref: '#/components/parameters/InspectionAfter'
        - $ref: '#/components/parameters/InspectionLimit'
        - name: state
          in: query
          required: false
          description: Node filter. Without lifecycle support every node is active.
          schema:
            type: string
            enum: [all, active, inactive]
            default: all
      responses:
        '200':
          description: One page of nodes
          headers:
            Cache-Control:
              schema:
                type: string
                const: no-store
            ETag:
              $ref: '#/components/headers/ETag'
            X-Knotrel-Instance-Id:
              $ref: '#/components/headers/X-Knotrel-Instance-Id'
            X-Knotrel-Graph-Id:
              $ref: '#/components/headers/X-Knotrel-Graph-Id'
            X-Knotrel-Generation:
              $ref: '#/components/headers/X-Knotrel-Generation'
            X-Knotrel-State-Version:
              $ref: '#/components/headers/X-Knotrel-State-Version'
            X-Knotrel-Source-Position:
              $ref: '#/components/headers/X-Knotrel-Source-Position'
            X-Knotrel-Sync-Status:
              $ref: '#/components/headers/X-Knotrel-Sync-Status'
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/NodePage'
              example:
                nodes:
                  - node: "2"
                    active: true
                    degree: 2
                  - node: "18446744073709551615"
                    active: false
                    degree: 1
                next_after: "18446744073709551615"
        '401':
          $ref: '#/components/responses/Unauthenticated'
        '403':
          $ref: '#/components/responses/Forbidden'
        '409':
          $ref: '#/components/responses/InspectionConflict'
        '422':
          $ref: '#/components/responses/InspectionInvalid'
        '503':
          $ref: '#/components/responses/InspectionUnavailable'

  /v1/nodes/{node}:
    get:
      x-knotrel-stability: experimental
      operationId: get_node
      x-knotrel-role: inspect
      summary: Inspect one node
      tags:
        - Inspection
      description: |
        Read-only inspection route (`KNOTREL_INSPECTION=true`). Returns the node's flag and
        registered degree. `degree` is `null` for engines without per-node adjacency (`ett`,
        `hdt`, and `cluster-forest` without lifecycle support; with lifecycle the degree comes
        from the topology catalog). Accepts no query parameters.
      parameters:
        - $ref: '#/components/parameters/InspectionNode'
      responses:
        '200':
          description: The registered node
          headers:
            Cache-Control:
              schema:
                type: string
                const: no-store
            ETag:
              $ref: '#/components/headers/ETag'
            X-Knotrel-Instance-Id:
              $ref: '#/components/headers/X-Knotrel-Instance-Id'
            X-Knotrel-Graph-Id:
              $ref: '#/components/headers/X-Knotrel-Graph-Id'
            X-Knotrel-Generation:
              $ref: '#/components/headers/X-Knotrel-Generation'
            X-Knotrel-State-Version:
              $ref: '#/components/headers/X-Knotrel-State-Version'
            X-Knotrel-Source-Position:
              $ref: '#/components/headers/X-Knotrel-Source-Position'
            X-Knotrel-Sync-Status:
              $ref: '#/components/headers/X-Knotrel-Sync-Status'
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/InspectedNode'
        '401':
          $ref: '#/components/responses/Unauthenticated'
        '403':
          $ref: '#/components/responses/Forbidden'
        '404':
          $ref: '#/components/responses/InspectionUnknownNode'
        '409':
          $ref: '#/components/responses/InspectionConflict'
        '422':
          $ref: '#/components/responses/InspectionInvalid'
        '503':
          $ref: '#/components/responses/InspectionUnavailable'

  /v1/nodes/{node}/edges:
    get:
      x-knotrel-stability: experimental
      operationId: list_node_edges
      x-knotrel-role: inspect
      summary: List one node's incident edges (inspection)
      tags:
        - Inspection
      description: |
        Read-only inspection route (`KNOTREL_INSPECTION=true`); requires `compact-bfs`
        (otherwise 409 `inspection_unsupported`). Order: ascending neighbor ID with lifecycle
        support, neighbor registration order without it. `after` is the last neighbor
        returned. With lifecycle support it need not be registered. Without it, it must name a
        registered node (nodes are never removed in that mode), otherwise 422
        `invalid_cursor`. Each page examines at most 10000 incidences. Same consistency
        rules as `GET /v1/nodes`.
      parameters:
        - $ref: '#/components/parameters/InspectionNode'
        - $ref: '#/components/parameters/InspectionAfter'
        - $ref: '#/components/parameters/InspectionLimit'
        - $ref: '#/components/parameters/InspectionEdgeState'
      responses:
        '200':
          description: One page of incident edges
          headers:
            Cache-Control:
              schema:
                type: string
                const: no-store
            ETag:
              $ref: '#/components/headers/ETag'
            X-Knotrel-Instance-Id:
              $ref: '#/components/headers/X-Knotrel-Instance-Id'
            X-Knotrel-Graph-Id:
              $ref: '#/components/headers/X-Knotrel-Graph-Id'
            X-Knotrel-Generation:
              $ref: '#/components/headers/X-Knotrel-Generation'
            X-Knotrel-State-Version:
              $ref: '#/components/headers/X-Knotrel-State-Version'
            X-Knotrel-Source-Position:
              $ref: '#/components/headers/X-Knotrel-Source-Position'
            X-Knotrel-Sync-Status:
              $ref: '#/components/headers/X-Knotrel-Sync-Status'
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/IncidentEdgePage'
        '401':
          $ref: '#/components/responses/Unauthenticated'
        '403':
          $ref: '#/components/responses/Forbidden'
        '404':
          $ref: '#/components/responses/InspectionUnknownNode'
        '409':
          $ref: '#/components/responses/InspectionConflict'
        '422':
          $ref: '#/components/responses/InspectionInvalid'
        '503':
          $ref: '#/components/responses/InspectionUnavailable'

  /v1/edges:
    get:
      x-knotrel-stability: experimental
      operationId: list_edges
      x-knotrel-role: inspect
      summary: List edges once each (inspection)
      tags:
        - Inspection
      description: |
        Read-only inspection route (`KNOTREL_INSPECTION=true`); requires `compact-bfs`.
        Each edge appears once as `source < target`, ordered by `source` ascending and then by
        `source`'s incidence order. Resume with `after_source` and, when present,
        `after_target` from `next_after_source` / `next_after_target`. A page examines at most
        10000 nodes plus incidences. Same consistency rules as `GET /v1/nodes`.
      parameters:
        - name: after_source
          in: query
          required: false
          description: Resume position (`next_after_source` of the previous page).
          schema:
            $ref: '#/components/schemas/NodeId'
        - name: after_target
          in: query
          required: false
          description: Resume position inside `after_source` (`next_after_target`); requires `after_source`.
          schema:
            $ref: '#/components/schemas/NodeId'
        - $ref: '#/components/parameters/InspectionLimit'
        - $ref: '#/components/parameters/InspectionEdgeState'
      responses:
        '200':
          description: One page of edges
          headers:
            Cache-Control:
              schema:
                type: string
                const: no-store
            ETag:
              $ref: '#/components/headers/ETag'
            X-Knotrel-Instance-Id:
              $ref: '#/components/headers/X-Knotrel-Instance-Id'
            X-Knotrel-Graph-Id:
              $ref: '#/components/headers/X-Knotrel-Graph-Id'
            X-Knotrel-Generation:
              $ref: '#/components/headers/X-Knotrel-Generation'
            X-Knotrel-State-Version:
              $ref: '#/components/headers/X-Knotrel-State-Version'
            X-Knotrel-Source-Position:
              $ref: '#/components/headers/X-Knotrel-Source-Position'
            X-Knotrel-Sync-Status:
              $ref: '#/components/headers/X-Knotrel-Sync-Status'
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/EdgePage'
        '401':
          $ref: '#/components/responses/Unauthenticated'
        '403':
          $ref: '#/components/responses/Forbidden'
        '409':
          $ref: '#/components/responses/InspectionConflict'
        '422':
          $ref: '#/components/responses/InspectionInvalid'
        '503':
          $ref: '#/components/responses/InspectionUnavailable'

  /v1/graphs:
    get:
      x-knotrel-stability: experimental
      operationId: list_graphs
      x-knotrel-role: read
      summary: List the caller's tenant's graphs
      tags:
        - Graphs
      description: |
        Graph resources (experimental, new in 1.3). Lists the graphs owned by the caller's
        tenant: the principal's tenant with `KNOTREL_AUTH=gateway-identity`, or the local
        tenant without authentication. Another tenant's graphs are never listed. The default
        graph of the single-graph routes is not a graph resource and is never listed; neither
        is a graph being deleted. Ordered by identifier text (identifiers carry no order of
        their own); a page reflects the registry at one instant. Reads graph records only,
        never graph content or the graph lock. Records live in memory and are lost on restart.
      parameters:
        - $ref: '#/components/parameters/TenantSelection'
        - name: limit
          in: query
          required: false
          description: Page size.
          schema:
            type: integer
            minimum: 1
            maximum: 100
            default: 50
        - name: after
          in: query
          required: false
          description: |
            Exclusive cursor: the last `id` of the previous page (`next_after`). It must be a
            well-formed graph identifier (422 `invalid_cursor` otherwise) but need not exist.
          schema:
            $ref: '#/components/schemas/GraphId'
      responses:
        '200':
          description: One page of graphs
          headers:
            Cache-Control:
              schema:
                type: string
                const: no-store
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/GraphList'
        '401':
          $ref: '#/components/responses/Unauthenticated'
        '403':
          $ref: '#/components/responses/GraphForbidden'
        '422':
          $ref: '#/components/responses/GraphInvalid'
        '503':
          $ref: '#/components/responses/DrainingOrTimeout'
    post:
      x-knotrel-stability: experimental
      operationId: create_graph
      x-knotrel-role: graph-admin
      summary: Create an empty graph owned by the caller's tenant
      tags:
        - Graphs
      description: |
        Creates an empty graph with a server-generated identifier, owned by the caller's
        tenant (never taken from the body). Engine and mode default to the server's
        `KNOTREL_ENGINE` and `KNOTREL_MODE`; graph limits, topology lifecycle, inspection and
        the deduplication window follow the server configuration. Every graph a tenant creates
        counts against `KNOTREL_TENANT_MAX_GRAPHS` (409 `graph_quota_exceeded`; a graph being
        deleted counts until it is removed).

        **Idempotency.** With an `Idempotency-Key`, a retry with the same key and the same body
        by the same tenant within 24 hours answers 201 with the graph the first request created
        (its current record), or 404 `graph_not_found` if it was deleted meanwhile; the same key
        with a different body answers 422 `idempotency_key_reused`. At most 256 keys are kept per
        tenant (oldest evicted first), in memory: they are lost on restart. Failed creations are
        not remembered.
      parameters:
        - $ref: '#/components/parameters/TenantSelection'
        - name: Idempotency-Key
          in: header
          required: false
          description: 1 to 64 bytes of printable ASCII, at most once.
          schema:
            type: string
            minLength: 1
            maxLength: 64
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/GraphCreateRequest'
            example:
              name: billing
              environment: staging
              metadata:
                team: payments
      responses:
        '201':
          description: Created (or, for a retried idempotency key, the graph created before)
          headers:
            Location:
              description: '`/v1/graphs/{graph_id}`'
              schema:
                type: string
            ETag:
              $ref: '#/components/headers/GraphETag'
            Cache-Control:
              schema:
                type: string
                const: no-store
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/GraphResource'
        '400':
          $ref: '#/components/responses/GraphMalformed'
        '401':
          $ref: '#/components/responses/Unauthenticated'
        '403':
          $ref: '#/components/responses/GraphForbidden'
        '404':
          $ref: '#/components/responses/GraphNotFound'
        '409':
          description: The tenant's graph quota is reached (`graph_quota_exceeded`).
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorOutcome'
        '413':
          $ref: '#/components/responses/GraphMalformed'
        '415':
          $ref: '#/components/responses/GraphMalformed'
        '422':
          $ref: '#/components/responses/GraphInvalid'
        '503':
          description: >-
            Draining (`shutting_down`), request timeout (`request_timeout`), or no identifier could
            be generated (`unavailable`).
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorOutcome'

  /v1/graphs/{graph_id}:
    parameters:
      - $ref: '#/components/parameters/GraphIdPath'
    get:
      x-knotrel-stability: experimental
      operationId: get_graph
      x-knotrel-role: read
      summary: Read one graph resource
      tags:
        - Graphs
      description: |
        Reads the graph's record and status. Another tenant's graph, a graph being deleted,
        an unknown and a malformed identifier all answer the same 404 `graph_not_found`.
      parameters:
        - $ref: '#/components/parameters/TenantSelection'
      responses:
        '200':
          description: The graph resource
          headers:
            ETag:
              $ref: '#/components/headers/GraphETag'
            Cache-Control:
              schema:
                type: string
                const: no-store
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/GraphResource'
        '401':
          $ref: '#/components/responses/Unauthenticated'
        '403':
          $ref: '#/components/responses/GraphForbidden'
        '404':
          $ref: '#/components/responses/GraphNotFound'
        '422':
          $ref: '#/components/responses/GraphInvalid'
        '503':
          $ref: '#/components/responses/DrainingOrTimeout'
    patch:
      x-knotrel-stability: experimental
      operationId: update_graph
      x-knotrel-role: graph-admin
      summary: Change a graph's descriptive fields (JSON Merge Patch)
      tags:
        - Graphs
      description: |
        JSON Merge Patch (RFC 7396) of `name`, `description`, `environment` and `metadata`:
        a string sets a field, `null` removes it; inside `metadata`, a string sets a key and
        `null` removes it, and `"metadata": null` removes every key. Any other member answers
        422. A change increments `revision`; a patch that changes nothing keeps it.

        **Conditional update.** `If-Match` is optional. With it, the patch applies only if one
        of its strong tags equals the current `ETag` (`*` matches any existing graph), compared
        atomically with the change; otherwise 412 `precondition_failed` and nothing changes.
        Weak tags never match.
      parameters:
        - $ref: '#/components/parameters/TenantSelection'
        - $ref: '#/components/parameters/GraphIfMatch'
      requestBody:
        required: true
        content:
          application/merge-patch+json:
            schema:
              $ref: '#/components/schemas/GraphPatchRequest'
          application/json:
            schema:
              $ref: '#/components/schemas/GraphPatchRequest'
      responses:
        '200':
          description: The graph resource after the patch
          headers:
            ETag:
              $ref: '#/components/headers/GraphETag'
            Cache-Control:
              schema:
                type: string
                const: no-store
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/GraphResource'
        '400':
          $ref: '#/components/responses/GraphMalformed'
        '401':
          $ref: '#/components/responses/Unauthenticated'
        '403':
          $ref: '#/components/responses/GraphForbidden'
        '404':
          $ref: '#/components/responses/GraphNotFound'
        '412':
          $ref: '#/components/responses/GraphPreconditionFailed'
        '413':
          $ref: '#/components/responses/GraphMalformed'
        '415':
          $ref: '#/components/responses/GraphMalformed'
        '422':
          $ref: '#/components/responses/GraphInvalid'
        '503':
          $ref: '#/components/responses/DrainingOrTimeout'
    delete:
      x-knotrel-stability: experimental
      operationId: delete_graph
      x-knotrel-role: graph-admin
      summary: Delete a graph
      tags:
        - Graphs
      description: |
        The graph stops being found and refuses new work at once; admitted work finishes. The
        request then waits up to half of `KNOTREL_REQUEST_TIMEOUT_MS` (at most 30 s) and answers
        204 when the graph is removed, or 202 while admitted work still drains; after either,
        the graph answers 404 and its quota slot is freed when the drain completes. There is no
        soft delete: the graph's content and record are dropped. `If-Match` is optional and
        works as for `PATCH` (412 `precondition_failed`, nothing deleted).
      parameters:
        - $ref: '#/components/parameters/TenantSelection'
        - $ref: '#/components/parameters/GraphIfMatch'
      responses:
        '202':
          description: Deletion accepted; admitted work is still draining.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/GraphDeleting'
        '204':
          description: The graph was removed.
        '401':
          $ref: '#/components/responses/Unauthenticated'
        '403':
          $ref: '#/components/responses/GraphForbidden'
        '404':
          $ref: '#/components/responses/GraphNotFound'
        '412':
          $ref: '#/components/responses/GraphPreconditionFailed'
        '422':
          $ref: '#/components/responses/GraphInvalid'
        '503':
          $ref: '#/components/responses/DrainingOrTimeout'

  /v1/snapshots:
    post:
      x-knotrel-stability: experimental
      operationId: create_snapshot
      x-knotrel-role: graph-admin
      summary: Take a snapshot of the default graph
      tags:
        - Snapshots
      description: |
        Experimental, new in 1.3 ([ADR 0016](architecture/0016-authority-snapshots-and-restore.md)).
        Requires `KNOTREL_SNAPSHOT_DIR`, which only source-managed mode accepts; the request body
        is ignored. One snapshot at a time.

        A read job on the shared admission lane copies the graph (every node and edge with
        its flag) and its progress (generation, `state_version`, source ID, epoch, applied
        position and delivery sequence) under the graph read lock: queries keep running, and
        feeder writes wait only for the in-memory copy. Encoding, `fsync`, rename and retention
        then run off-lock. The snapshot is exactly the graph at its applied source position;
        it is taken in `catching_up`, `ready` and `stale`.

        A failure (disk full, permissions) answers 503 `snapshot_failed`, keeps the earlier
        snapshots and never changes the graph. A retention failure after a durable publication
        still answers 200 and is logged. A caller that goes away does not stop a started
        publication. The directory path is never exposed.
      responses:
        '200':
          description: The snapshot is durable.
          headers:
            Cache-Control:
              schema:
                type: string
                const: no-store
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/SnapshotCreated'
        '401':
          $ref: '#/components/responses/Unauthenticated'
        '403':
          $ref: '#/components/responses/Forbidden'
        '409':
          description: |
            `snapshots_disabled` (no `KNOTREL_SNAPSHOT_DIR`; before admission),
            `snapshot_in_progress` (another snapshot is being taken; before admission),
            `graph_uninitialized` (no generation yet, including while a baseline loads) or
            `graph_desynchronized`.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorOutcome'
        '503':
          description: |
            `snapshot_failed` (encoding or the store failed; earlier snapshots are unchanged),
            admission exhausted (`busy`), worker unavailable (`unavailable`), draining
            (`shutting_down`) or `request_timeout` (a started publication may still complete).
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorOutcome'

components:
  securitySchemes:
    GatewayIdentity:
      type: apiKey
      in: header
      name: X-Knotrel-Auth-Subject
      description: |
        Gateway-verified identity (`KNOTREL_AUTH=gateway-identity`; experimental, new in 1.3).
        Not a client credential: a trusted gateway authenticates the client by its own means and
        **overwrites** these headers on every forwarded request, and only trusted peers can
        reach the listener. All headers are case-insensitive and must appear at most once.

        - `X-Knotrel-Auth-Subject` (required): 1–256 bytes of printable ASCII, no leading or
          trailing space.
        - `X-Knotrel-Auth-Tenant` (optional): `^[a-z0-9][a-z0-9_-]{0,62}$`.
        - `X-Knotrel-Auth-Roles` (optional, absent = no roles): comma-separated, at most 16, from
          `probe`, `metrics`, `read`, `inspect`, `mutate`, `feeder-control`, `feeder-data`,
          `import`, `graph-admin`, `tenant-admin`. Each role grants only the action of the same
          name; `tenant-admin` also lets the graph resource routes act on another tenant
          (`tenant` parameter), still with each operation's own role.

        The tenant header is the only source of the tenant that owns graph resources
        (`/v1/graphs`); a principal without one cannot use those routes (403).

        Any other header starting with `X-Knotrel-Auth-`, a repeated header, a malformed value or
        an unknown role answers 401 `unauthenticated`. With `KNOTREL_AUTH_TRUSTED_PEERS` set, a
        request from a connection whose peer address is not listed also answers 401.
  parameters:
    InspectionNode:
      name: node
      in: path
      required: true
      description: Node ID (ASCII decimal digits, u64; leading zeroes are normalized). A segment that
        does not percent-decode to UTF-8 (for example `%FF`) is an invalid node ID (422
        `invalid_request`), or 409 `inspection_disabled` when inspection is off.
      schema:
        $ref: '#/components/schemas/NodeId'
    InspectionAfter:
      name: after
      in: query
      required: false
      description: Exclusive cursor, the last node (or neighbor) of the previous page. Never expires.
      schema:
        $ref: '#/components/schemas/NodeId'
    InspectionLimit:
      name: limit
      in: query
      required: false
      description: Page size.
      schema:
        type: integer
        minimum: 1
        maximum: 1000
        default: 100
    InspectionEdgeState:
      name: state
      in: query
      required: false
      description: Edge filter. Without lifecycle support every edge is enabled and effective.
      schema:
        type: string
        enum: [all, enabled, disabled, effective, ineffective]
        default: all
    GraphIdPath:
      name: graph_id
      in: path
      required: true
      description: The graph identifier. A malformed identifier answers 404 `graph_not_found`.
      schema:
        type: string
    TenantSelection:
      name: tenant
      in: query
      required: false
      description: |
        Administrative tenant selection: act on this tenant's graphs instead of the principal's
        own. Honored only with `KNOTREL_AUTH=gateway-identity` for a principal holding the
        `tenant-admin` role, which still needs the operation's own role (403 `forbidden`
        otherwise). Without authentication, or when malformed, it answers 422
        `invalid_request`.
      schema:
        type: string
        pattern: '^[a-z0-9][a-z0-9_-]{0,62}$'
    GraphIfMatch:
      name: If-Match
      in: header
      required: false
      description: Strong entity tags (`"<revision>"`) or `*`; see the operation description.
      schema:
        type: string
  responses:
    Unauthenticated:
      description: >-
        Only with `KNOTREL_AUTH=gateway-identity`: the identity is missing or invalid, or the peer is
        not trusted (`unauthenticated`). The message is fixed and never echoes a header value.
      headers:
        WWW-Authenticate:
          description: Always `KnotrelGateway realm="knotrel"`.
          schema:
            type: string
            const: KnotrelGateway realm="knotrel"
      content:
        application/json:
          schema:
            $ref: '#/components/schemas/ErrorOutcome'
          example:
            result: error
            code: unauthenticated
            message: missing or invalid gateway identity
    Forbidden:
      description: >-
        Only with `KNOTREL_AUTH=gateway-identity`: the principal lacks the role this operation needs
        (`forbidden`). Checked before the body is validated and before admission; for operations
        and batches, before any operation is applied.
      content:
        application/json:
          schema:
            $ref: '#/components/schemas/ErrorOutcome'
          example:
            result: error
            code: forbidden
            message: the principal is not allowed to perform this action
    RequestTimeout:
      description: >-
        The request exceeded `KNOTREL_REQUEST_TIMEOUT_MS` (`request_timeout`, with `Connection: close`).
      content:
        application/json:
          schema:
            $ref: '#/components/schemas/ErrorOutcome'
    DrainingOrTimeout:
      description: >-
        The server is draining (`shutting_down`, with `Connection: close`) or the request exceeded
        `KNOTREL_REQUEST_TIMEOUT_MS` (`request_timeout`).
      content:
        application/json:
          schema:
            $ref: '#/components/schemas/ErrorOutcome'
    InspectionConflict:
      description: |
        `inspection_disabled` (KNOTREL_INSPECTION is not enabled; rejected before admission)
        or `inspection_unsupported` (incident and edge listing on `ett` or `hdt`, or on
        `cluster-forest` without lifecycle support).
      headers:
        Cache-Control:
          schema:
            type: string
            const: no-store
      content:
        application/json:
          schema:
            $ref: '#/components/schemas/ErrorOutcome'
    InspectionInvalid:
      description: |
        `invalid_request`: unknown, repeated or malformed query parameter, invalid node ID
        (including a path segment that is not UTF-8 after percent-decoding), `limit` outside 1-1000, unknown `state`, `after_target` without `after_source`.
        `invalid_cursor`: a plain `compact-bfs` incidence cursor names an unregistered node.
        The query-string errors (`invalid_request`) are returned before the inspection path and
        carry no `Cache-Control` header; `invalid_cursor` carries `no-store`.
      content:
        application/json:
          schema:
            $ref: '#/components/schemas/ErrorOutcome'
    InspectionUnknownNode:
      description: The inspected node is not registered (`unknown_node`).
      content:
        application/json:
          schema:
            $ref: '#/components/schemas/ErrorOutcome'
    InspectionUnavailable:
      description: Admission exhausted (`busy`), worker unavailable, draining or `request_timeout`.
      content:
        application/json:
          schema:
            $ref: '#/components/schemas/ErrorOutcome'
    GraphNotFound:
      description: >-
        No graph with this identifier is visible to the caller's tenant (`graph_not_found`): another
        tenant's graph, a graph being deleted, an unknown or a malformed identifier, all alike.
      content:
        application/json:
          schema:
            $ref: '#/components/schemas/ErrorOutcome'
          example:
            result: error
            code: graph_not_found
            message: graph not found
    GraphForbidden:
      description: >-
        Only with `KNOTREL_AUTH=gateway-identity` (`forbidden`): the principal lacks the operation's
        role, has no tenant, or selects another tenant without `tenant-admin`. Checked before any
        graph lookup, so it reveals nothing about which graphs exist.
      content:
        application/json:
          schema:
            $ref: '#/components/schemas/ErrorOutcome'
    GraphInvalid:
      description: >-
        `invalid_request`: a field or metadata bound, a reserved `knotrel.` key, an unknown member,
        an unsupported engine or mode, a malformed `Idempotency-Key`, `limit` or `tenant`
        parameter; `invalid_cursor`: a malformed `after`; `idempotency_key_reused`: the key was used
        with a different body. Messages name the rule, never the value.
      content:
        application/json:
          schema:
            $ref: '#/components/schemas/ErrorOutcome'
    GraphMalformed:
      description: >-
        `invalid_request`: malformed JSON or an unreadable body (400), a body over 1 MiB (413), or
        a `Content-Type` other than JSON (415).
      content:
        application/json:
          schema:
            $ref: '#/components/schemas/ErrorOutcome'
    GraphPreconditionFailed:
      description: '`If-Match` matches no current revision (`precondition_failed`); nothing changed.'
      content:
        application/json:
          schema:
            $ref: '#/components/schemas/ErrorOutcome'
  headers:
    ETag:
      description: |
        Replacement token `"<generation>.<state_version>.<encoded source position>"`.
        The position segment is empty when no source position exists (standalone mode).
      schema:
        type: string
      example: '"1.0.pos-1"'
    X-Knotrel-Instance-Id:
      description: Identifier of the serving process instance.
      schema:
        type: string
    X-Knotrel-Graph-Id:
      description: Graph identifier; always `default`.
      schema:
        type: string
        const: default
    X-Knotrel-Generation:
      description: Published graph generation; `0` in standalone mode.
      schema:
        type: string
        pattern: '^[0-9]+$'
    X-Knotrel-State-Version:
      description: |
        Instance-local revision as an arbitrary-precision decimal string. It advances
        once per effective mutation (`changed: true`).
      schema:
        type: string
        pattern: '^[0-9]+$'
    X-Knotrel-Source-Position:
      description: Percent-encoded applied source position. Present only when one exists.
      schema:
        type: string
    X-Knotrel-Sync-Status:
      description: Synchronization status. Present only in source-managed mode.
      schema:
        type: string
        enum: [uninitialized, loading, catching_up, ready, stale, desynchronized]
    GraphETag:
      description: |
        Strong tag of the graph record's revision, `"<revision>"`. Usable in `If-Match` on
        `PATCH` and `DELETE /v1/graphs/{graph_id}`. Unrelated to the graph state `ETag` of the
        single-graph routes.
      schema:
        type: string
        pattern: '^"[0-9]+"$'
      example: '"3"'
  schemas:
    GraphId:
      type: string
      description: |
        Opaque, server-generated graph identifier: `g_` followed by a lowercase, hyphenated
        UUID v4. Do not parse or order it.
      pattern: '^g_[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$'
      example: g_0b9f3c52-7a41-4e8d-9c6f-2d1e5a7b8c90
    GraphMetadata:
      type: object
      description: |
        Descriptive string metadata, returned to every principal that may read the graph: do
        not store secrets. At most 16 entries; keys match `^[a-z0-9][a-z0-9._-]*$` with at most
        64 bytes and must not start with the reserved prefix `knotrel.`; values are UTF-8
        without control characters, at most 256 bytes; keys and values total at most 4096
        bytes. Not indexed: there is no filtering by metadata.
      maxProperties: 16
      propertyNames:
        pattern: '^[a-z0-9][a-z0-9._-]{0,63}$'
      additionalProperties:
        type: string
        maxLength: 256
    GraphResource:
      type: object
      description: A graph resource (experimental, new in 1.3). Every member is always present.
      required: [id, object, tenant, created_at, revision, engine, mode, status, name,
                 description, environment, metadata]
      properties:
        id:
          $ref: '#/components/schemas/GraphId'
        object:
          type: string
          const: graph
        tenant:
          type: [string, 'null']
          description: The owning tenant; `null` for the local tenant (no authentication).
        created_at:
          type: string
          format: date-time
          description: Creation time, RFC 3339 UTC with whole seconds.
          example: '2026-11-30T10:15:00Z'
        revision:
          type: string
          pattern: '^[1-9][0-9]*$'
          description: >-
            Revision of the record (decimal string), starting at 1 and incremented by every change.
            Not the graph's state version.
        engine:
          type: [string, 'null']
          enum: [compact-bfs, ett, hdt, cluster-forest, null]
        mode:
          type: [string, 'null']
          enum: [standalone, source_managed, null]
        status:
          type: string
          enum: [loading, active, failed, deleting]
        name:
          type: [string, 'null']
          maxLength: 128
        description:
          type: [string, 'null']
          maxLength: 256
        environment:
          type: [string, 'null']
          description: Descriptive label only; it grants and isolates nothing.
          pattern: '^[a-z0-9][a-z0-9-]{0,31}$'
        metadata:
          $ref: '#/components/schemas/GraphMetadata'
    GraphCreateRequest:
      type: object
      additionalProperties: false
      description: Every member is optional; server-generated fields cannot be set.
      properties:
        name:
          type: string
          maxLength: 128
          description: UTF-8 without control characters, at most 128 bytes.
        description:
          type: string
          maxLength: 256
          description: UTF-8 without control characters, at most 256 bytes.
        environment:
          type: string
          pattern: '^[a-z0-9][a-z0-9-]{0,31}$'
        metadata:
          $ref: '#/components/schemas/GraphMetadata'
        engine:
          type: string
          enum: [compact-bfs, ett, hdt, cluster-forest]
          description: >-
            Defaults to `KNOTREL_ENGINE`. With `KNOTREL_TOPOLOGY_LIFECYCLE=true`, only `compact-bfs`
            and `cluster-forest`.
        mode:
          type: string
          enum: [standalone, source_managed]
          description: Defaults to `KNOTREL_MODE`. Recorded on the resource.
    GraphPatchRequest:
      type: object
      additionalProperties: false
      description: JSON Merge Patch (RFC 7396) of the descriptive fields.
      properties:
        name:
          type: [string, 'null']
          maxLength: 128
        description:
          type: [string, 'null']
          maxLength: 256
        environment:
          type: [string, 'null']
          pattern: '^[a-z0-9][a-z0-9-]{0,31}$'
        metadata:
          type: [object, 'null']
          additionalProperties:
            type: [string, 'null']
            maxLength: 256
    GraphList:
      type: object
      required: [graphs, next_after]
      properties:
        graphs:
          type: array
          maxItems: 100
          items:
            $ref: '#/components/schemas/GraphResource'
        next_after:
          description: Cursor of the next page, or `null` when this page is the last.
          oneOf:
            - $ref: '#/components/schemas/GraphId'
            - type: 'null'
    GraphDeleting:
      type: object
      required: [status]
      properties:
        status:
          type: string
          const: deleting
    NodeId:
      type: string
      pattern: '^[0-9]+$'
      description: |
        Nonempty string of ASCII decimal digits representing an unsigned 64-bit integer
        (0 through 18446744073709551615). Leading zeroes are accepted and normalized.
      example: "42"

    AddNodeOperation:
      type: object
      required:
        - op
        - node
      additionalProperties: false
      properties:
        op:
          type: string
          enum: [add_node]
        node:
          $ref: '#/components/schemas/NodeId'

    LinkOperation:
      type: object
      required:
        - op
        - source
        - target
      additionalProperties: false
      properties:
        op:
          type: string
          enum: [link]
        source:
          $ref: '#/components/schemas/NodeId'
        target:
          $ref: '#/components/schemas/NodeId'

    CutOperation:
      type: object
      required:
        - op
        - source
        - target
      additionalProperties: false
      properties:
        op:
          type: string
          enum: [cut]
        source:
          $ref: '#/components/schemas/NodeId'
        target:
          $ref: '#/components/schemas/NodeId'

    ConnectedOperation:
      type: object
      required:
        - op
        - source
        - target
      additionalProperties: false
      properties:
        op:
          type: string
          enum: [connected]
        source:
          $ref: '#/components/schemas/NodeId'
        target:
          $ref: '#/components/schemas/NodeId'

    SetNodeActiveOperation:
      type: object
      description: Lifecycle support only. Sets the node's `active` flag.
      required:
        - op
        - node
        - active
      additionalProperties: false
      properties:
        op:
          type: string
          enum: [set_node_active]
        node:
          $ref: '#/components/schemas/NodeId'
        active:
          type: boolean

    SetEdgeEnabledOperation:
      type: object
      description: Lifecycle support only. Sets the registered edge's `enabled` flag.
      required:
        - op
        - source
        - target
        - enabled
      additionalProperties: false
      properties:
        op:
          type: string
          enum: [set_edge_enabled]
        source:
          $ref: '#/components/schemas/NodeId'
        target:
          $ref: '#/components/schemas/NodeId'
        enabled:
          type: boolean

    RemoveNodeOperation:
      type: object
      description: Lifecycle support only. Removes the node and every incident registered edge.
      required:
        - op
        - node
      additionalProperties: false
      properties:
        op:
          type: string
          enum: [remove_node]
        node:
          $ref: '#/components/schemas/NodeId'

    NodeStateOperation:
      type: object
      description: Lifecycle support only. Query; an absent node is not an error.
      required:
        - op
        - node
      additionalProperties: false
      properties:
        op:
          type: string
          enum: [node_state]
        node:
          $ref: '#/components/schemas/NodeId'

    EdgeStateOperation:
      type: object
      description: |
        Lifecycle support only. Query; an absent edge is not an error. `source == target`
        returns `self_loop`.
      required:
        - op
        - source
        - target
      additionalProperties: false
      properties:
        op:
          type: string
          enum: [edge_state]
        source:
          $ref: '#/components/schemas/NodeId'
        target:
          $ref: '#/components/schemas/NodeId'

    Operation:
      oneOf:
        - $ref: '#/components/schemas/AddNodeOperation'
        - $ref: '#/components/schemas/LinkOperation'
        - $ref: '#/components/schemas/CutOperation'
        - $ref: '#/components/schemas/ConnectedOperation'
        - $ref: '#/components/schemas/SetNodeActiveOperation'
        - $ref: '#/components/schemas/SetEdgeEnabledOperation'
        - $ref: '#/components/schemas/RemoveNodeOperation'
        - $ref: '#/components/schemas/NodeStateOperation'
        - $ref: '#/components/schemas/EdgeStateOperation'
      discriminator:
        propertyName: op
        mapping:
          add_node: '#/components/schemas/AddNodeOperation'
          link: '#/components/schemas/LinkOperation'
          cut: '#/components/schemas/CutOperation'
          connected: '#/components/schemas/ConnectedOperation'
          set_node_active: '#/components/schemas/SetNodeActiveOperation'
          set_edge_enabled: '#/components/schemas/SetEdgeEnabledOperation'
          remove_node: '#/components/schemas/RemoveNodeOperation'
          node_state: '#/components/schemas/NodeStateOperation'
          edge_state: '#/components/schemas/EdgeStateOperation'

    ChangedOutcome:
      type: object
      required:
        - result
        - changed
      properties:
        result:
          type: string
          enum: [changed]
        changed:
          type: boolean
          description: True if graph connectivity structure changed; false for no-ops.

    ConnectedOutcome:
      type: object
      required:
        - result
        - connected
      properties:
        result:
          type: string
          enum: [connected]
        connected:
          type: boolean
          description: True if both vertices belong to the same connected component.

    NodeStateOutcome:
      type: object
      description: |
        Result of `node_state`. An absent node reports `registered: false` and
        `active: false`.
      required:
        - result
        - registered
        - active
      properties:
        result:
          type: string
          enum: [node_state]
        registered:
          type: boolean
        active:
          type: boolean

    EdgeStateOutcome:
      type: object
      description: |
        Result of `edge_state`. `effective` means enabled with both endpoints active. An
        absent edge reports `registered: false` and `false` flags.
      required:
        - result
        - registered
        - enabled
        - effective
      properties:
        result:
          type: string
          enum: [edge_state]
        registered:
          type: boolean
        enabled:
          type: boolean
        effective:
          type: boolean

    ErrorCode:
      type: string
      description: |
        Machine-readable error code. Clients should branch on it, not on the message, and handle an
        unknown code as an error of its status class.

        `too_many_connections` is not produced by any operation: the accept loop writes a static
        `503` with this code to a connection opened beyond `KNOTREL_MAX_CONNECTIONS`, before any
        request is read, and closes it (best effort; a client may instead see a reset).
        `busy` is the code of every exhausted admission lane (shared, feeder data, feeder control);
        `import_in_progress` only means that another import holds the import permit.

        Every code, its status and where it is produced (inspection codes belong to the
        experimental inspection routes). In a batch, per-operation errors appear in the results of
        a 200, without a status of their own.

        | Code | Status | Where |
        | --- | --- | --- |
        | `barrier_not_reached` | 409 | barrier: `barrier_delivery_sequence` ahead of the applied sequence |
        | `barrier_position_mismatch` | 409 | barrier: equal sequence, different `barrier_source_position` (when supplied) |
        | `busy` | 503 | the request's admission lane is exhausted: operations, batch, stats, inspection (shared lane); session, heartbeat (feeder control lane); events, barrier, gap (feeder data lane) |
        | `conflicting_duplicate` | 409 | events: retained sequence with a different `event_id` or payload, or a retained `event_id` reused; desynchronizes |
        | `desynchronized` | 503 | operations in source-managed mode while the graph is desynchronized; in a batch, every item of a 200 |
        | `direct_mutation_disabled` | 409 | operations, batch: a mutation in source-managed mode |
        | `edge_limit_exceeded` | 422 | operations, batch items, events, import |
        | `event_failed` | 422 | events: top-level `code` of a multi-event partial failure caused by a graph-domain error; the domain code is in `error.code` |
        | `fenced_feeder_session` | 409 | session (older epoch), heartbeat, import, events, gap, barrier |
        | `forbidden` | 403 | every route, only with `KNOTREL_AUTH=gateway-identity`: the principal lacks the operation's role |
        | `generation_exhausted` | 409 | import: the generation counter cannot advance |
        | `graph_already_initialized` | 409 | import: `create_only` on an initialized graph |
        | `graph_desynchronized` | 409 | events, barrier, snapshots: the graph is desynchronized |
        | `graph_not_found` | 404 | graph resources: no graph with this ID visible to the caller's tenant (another tenant's, deleting, unknown or malformed; experimental) |
        | `graph_quota_exceeded` | 409 | `POST /v1/graphs`: the tenant's `KNOTREL_TENANT_MAX_GRAPHS` is reached (experimental) |
        | `graph_uninitialized` | 409 | events, gap, barrier, snapshots: no baseline imported |
        | `idempotency_key_reused` | 422 | `POST /v1/graphs`: the `Idempotency-Key` was used with a different body (experimental) |
        | `import_in_progress` | 503 | import: another import holds the import permit (before the body is read) |
        | `inspection_disabled` | 409 | inspection routes, inspection off (experimental) |
        | `inspection_unsupported` | 409 | `GET /v1/nodes/{node}/edges`, `GET /v1/edges` on an engine without adjacency (experimental) |
        | `invalid_batch_size` | 422 | batch: not 1–1024 operations |
        | `invalid_cursor` | 422 | inspection: the cursor names an unregistered node; `GET /v1/graphs`: a malformed `after` (experimental) |
        | `invalid_edge` | 422 | events, import: an edge the graph refuses for a reason other than a self-loop or a limit; with lifecycle support, a conflicting duplicate edge in an import |
        | `invalid_graph_id` | 400 | import, events, gap, barrier: `graph_id` other than `default` |
        | `invalid_instance_id` | 400 | every feeder route: `X-Knotrel-Instance-Id` missing or not a valid header value |
        | `invalid_lease_duration` | 400 | session: `lease_duration_ms` outside 1000–60000 |
        | `invalid_node` | 422 | events, import: a node the graph refuses for a reason other than a limit; with lifecycle support, a conflicting duplicate node in an import |
        | `invalid_request` | 400, 413, 415, 422 | every JSON route: malformed JSON or a body that could not be read before its end, such as a client abort or malformed chunked encoding (400), body over 1 MiB on routes other than import (413), wrong `Content-Type` (415), shape, ID or bound violations (422); inspection and graph resource query errors (422) |
        | `lease_expired` | 409 | import, events, gap, barrier: the feeder lease expired |
        | `loading` | 503 | operations in source-managed mode while a baseline loads; in a batch, every item of a 200 |
        | `mode_conflict` | 409 | every feeder route in standalone mode |
        | `node_limit_exceeded` | 422 | operations, batch items, events, import |
        | `out_of_order_sequence` | 409 | events: delivery sequence gap; carries `expected_sequence` |
        | `payload_too_large` | 413 | import: body over `KNOTREL_MAX_IMPORT_BODY_BYTES`, declared by `Content-Length` or received; never another body read failure |
        | `precondition_failed` | 412 | import `replace`: missing or mismatching `If-Match`, or no initialized graph; `PATCH`/`DELETE /v1/graphs/{graph_id}`: mismatching `If-Match` |
        | `request_timeout` | 503 | any route: `KNOTREL_REQUEST_TIMEOUT_MS` exceeded; a state-changing outcome is unknown |
        | `self_loop` | 422 | operations, batch items, events, import |
        | `sequence_exhausted` | 409 | events: the delivery sequence cannot advance |
        | `session_required` | 409 | heartbeat, import, events, gap, barrier: no registered session |
        | `shutting_down` | 503 | every request except `GET`/`HEAD` on `/health`, `/ready` and `/metrics`, while draining (also unknown routes and other methods on those paths) |
        | `snapshot_failed` | 503 | snapshots: encoding or the snapshot store failed; earlier snapshots are unchanged (experimental) |
        | `snapshot_in_progress` | 409 | snapshots: another snapshot is being taken (experimental) |
        | `snapshots_disabled` | 409 | snapshots: no `KNOTREL_SNAPSHOT_DIR` (experimental) |
        | `source_epoch_mismatch` | 409 | events: different `source_epoch`; desynchronizes |
        | `source_mismatch` | 409 | events: different `source_id` |
        | `source_predecessor_mismatch` | 409 | events: `prev_delivery_sequence` or `prev_source_position` does not match; desynchronizes |
        | `stale_generation` | 409 | events, gap, barrier: `generation` is not the current one |
        | `stale_instance_id` | 409 | every feeder route: header or body `instance_id` of another process instance |
        | `superseded_barrier` | 409 | barrier: `barrier_delivery_sequence` behind the applied sequence |
        | `too_many_connections` | 503 | no route: written by the accept loop to a connection beyond `KNOTREL_MAX_CONNECTIONS`, before any request is read |
        | `topology_lifecycle_disabled` | 409 | operations, batch, events, import: a lifecycle operation, event or flag without lifecycle support |
        | `unauthenticated` | 401 | every route, only with `KNOTREL_AUTH=gateway-identity`: missing or invalid identity, or untrusted peer |
        | `unavailable` | 503 | every graph route: the graph worker failed (restart required); `POST /v1/graphs`: no identifier could be generated |
        | `uninitialized` | 503 | operations in source-managed mode before a baseline; in a batch, every item of a 200 |
        | `unknown_edge` | 404, 422 | operations: `set_edge_enabled` on an unregistered edge (404); the same as a batch item; lifecycle events (422) |
        | `unknown_node` | 404, 422 | operations: unknown query vertex or lifecycle node (404); the same as a batch item; inspection `GET /v1/nodes/{node}` and `/edges` (404); lifecycle events (422) |
        | `unverifiable_duplicate` | 409 | events: a retry of a sequence older than the deduplication window |
      enum:
        - barrier_not_reached
        - barrier_position_mismatch
        - busy
        - conflicting_duplicate
        - desynchronized
        - direct_mutation_disabled
        - edge_limit_exceeded
        - event_failed
        - fenced_feeder_session
        - forbidden
        - generation_exhausted
        - graph_already_initialized
        - graph_desynchronized
        - graph_not_found
        - graph_quota_exceeded
        - graph_uninitialized
        - idempotency_key_reused
        - import_in_progress
        - inspection_disabled
        - inspection_unsupported
        - invalid_batch_size
        - invalid_cursor
        - invalid_edge
        - invalid_graph_id
        - invalid_instance_id
        - invalid_lease_duration
        - invalid_node
        - invalid_request
        - lease_expired
        - loading
        - mode_conflict
        - node_limit_exceeded
        - out_of_order_sequence
        - payload_too_large
        - precondition_failed
        - request_timeout
        - self_loop
        - sequence_exhausted
        - session_required
        - shutting_down
        - snapshot_failed
        - snapshot_in_progress
        - snapshots_disabled
        - source_epoch_mismatch
        - source_mismatch
        - source_predecessor_mismatch
        - stale_generation
        - stale_instance_id
        - superseded_barrier
        - too_many_connections
        - topology_lifecycle_disabled
        - unauthenticated
        - unavailable
        - uninitialized
        - unknown_edge
        - unknown_node
        - unverifiable_duplicate

    ErrorOutcome:
      type: object
      required:
        - result
        - code
        - message
      properties:
        expected_sequence:
          $ref: '#/components/schemas/FeederU64'
        result:
          type: string
          enum: [error]
        code:
          $ref: '#/components/schemas/ErrorCode'
        message:
          type: string
          description: Human-readable error description.
          example: "unknown node: 3"

    Outcome:
      oneOf:
        - $ref: '#/components/schemas/ChangedOutcome'
        - $ref: '#/components/schemas/ConnectedOutcome'
        - $ref: '#/components/schemas/NodeStateOutcome'
        - $ref: '#/components/schemas/EdgeStateOutcome'
        - $ref: '#/components/schemas/ErrorOutcome'
      discriminator:
        propertyName: result
        mapping:
          changed: '#/components/schemas/ChangedOutcome'
          connected: '#/components/schemas/ConnectedOutcome'
          node_state: '#/components/schemas/NodeStateOutcome'
          edge_state: '#/components/schemas/EdgeStateOutcome'
          error: '#/components/schemas/ErrorOutcome'

    BatchRequest:
      type: object
      required:
        - operations
      additionalProperties: false
      properties:
        operations:
          type: array
          minItems: 1
          maxItems: 1024
          items:
            $ref: '#/components/schemas/Operation'

    BatchResponse:
      type: object
      required:
        - results
      properties:
        results:
          type: array
          items:
            $ref: '#/components/schemas/Outcome'

    HealthResponse:
      type: object
      required:
        - status
      properties:
        status:
          type: string
          enum: [ok]

    ReadinessReadyResponse:
      type: object
      required:
        - status
      properties:
        status:
          type: string
          enum: [ready]

    ReadinessNotReadyResponse:
      type: object
      required:
        - status
      properties:
        status:
          type: string
          enum: [starting, draining, unavailable, uninitialized, loading, catching_up, stale, desynchronized]
          description: |
            `starting`, `draining` and `unavailable` occur in both modes. The other values are
            reported only in source-managed mode.

    ServerInfo:
      type: object
      required:
        - engine
        - experimental
        - max_pending_jobs
        - max_body_bytes
        - max_batch_operations
        - max_nodes
        - max_edges
      properties:
        engine:
          type: string
          enum: [compact-bfs, ett, hdt, cluster-forest]
          description: |
            Configured connectivity engine. `cluster-forest` is new in 1.1 (stable value,
            experimental engine, like `ett` and `hdt`).
        experimental:
          type: boolean
          description: |
            The configured engine's qualification (see `docs/compatibility.md` §2.2):
            `true` when the engine is qualified experimental as to performance,
            maturity and usage recommendation, which carry no promise. It is not a
            stability class: the engine's interfaces, including its `engine` value,
            are stable either way. `false` for `compact-bfs`; `true` for `ett`, `hdt`
            and `cluster-forest`, possibly for the whole 1.x series. The value may change from
            `true` to `false` in a minor release when an engine is promoted, which
            the release notes record, and never changes from `false` to `true` for
            an existing engine. Neither change is breaking.
        max_pending_jobs:
          type: integer
          description: Maximum queued plus running graph operations on the shared admission lane.
        feeder_reserved_jobs:
          type: integer
          minimum: 1
          maximum: 64
          description: |
            Present only in source-managed mode. Admission permits reserved for feeder events,
            barriers and gap declarations (`KNOTREL_FEEDER_RESERVED_JOBS`, default 4); queries never
            use them. Feeder sessions and heartbeats have two further permits of their own.
        max_body_bytes:
          type: integer
          description: Maximum allowed request body size in bytes.
        max_batch_operations:
          type: integer
          description: Maximum operations in a single batch request.
        max_nodes:
          type: [integer, "null"]
          description: |
            Configured maximum node capacity (`KNOTREL_MAX_NODES`), or null if unlimited.
            With `cluster-forest` the enforced ceiling can be lower (the engine's
            capacity; see `docs/http-api.md`, graph capacity errors).
        max_edges:
          type: [integer, "null"]
          description: |
            Configured maximum edge capacity (`KNOTREL_MAX_EDGES`), or null if unlimited.
            With `cluster-forest` the enforced ceiling can be lower (the engine's
            capacity; see `docs/http-api.md`, graph capacity errors).
        topology_lifecycle:
          type: boolean
          const: true
          description: |
            Present, and `true`, only when node and edge lifecycle support is enabled
            (`KNOTREL_TOPOLOGY_LIFECYCLE=true`); absent otherwise.
        mode:
          type: string
          const: source_managed
          description: |
            Present only in source-managed mode (`KNOTREL_MODE=source_managed`). Absent in
            standalone mode. The response carries no server software version.
        inspection:
          type: boolean
          const: true
          description: |
            Present, and `true`, only when the read-only inspection routes are enabled
            (`KNOTREL_INSPECTION=true`); absent otherwise.
        instance_id:
          type: string
          description: |
            Present only in source-managed mode: the current process instance ID that feeder
            requests must carry. In both modes the same value is returned in the
            `X-Knotrel-Instance-Id` header of every response that carries the version headers:
            `/v1/stats`, `/v1/operations`, `/v1/batch`, the inspection routes and the feeder
            import, events, gap and barrier responses.
        authentication:
          type: string
          enum: [gateway-identity, custom]
          description: |
            Present only when an authentication extension is enabled (experimental, new in 1.3):
            `gateway-identity` (`KNOTREL_AUTH=gateway-identity`) or `custom` (an embedded
            caller's own authenticator); absent otherwise.
        persistence:
          type: string
          enum: [none, snapshot]
          description: |
            Present only in source-managed mode (experimental, new in 1.3, ADR 0016): `snapshot`
            with `KNOTREL_SNAPSHOT_DIR` (`POST /v1/snapshots` and restore at startup), `none`
            otherwise. The directory path is never exposed.

    GraphSnapshot:
      type: object
      required:
        - node_count
        - edge_count
        - max_nodes
        - max_edges
        - remaining_nodes
        - remaining_edges
        - state_version
      properties:
        node_count:
          type: integer
          minimum: 0
          description: Current count of registered vertices, active or inactive.
        edge_count:
          type: integer
          minimum: 0
          description: Current count of registered undirected edges, enabled or disabled.
        active_node_count:
          $ref: '#/components/schemas/ActiveNodeCount'
        enabled_edge_count:
          $ref: '#/components/schemas/EnabledEdgeCount'
        effective_edge_count:
          $ref: '#/components/schemas/EffectiveEdgeCount'
        max_nodes:
          type: [integer, "null"]
          description: Configured node limit ceiling, or null if unlimited.
        max_edges:
          type: [integer, "null"]
          description: Configured edge limit ceiling, or null if unlimited.
        remaining_nodes:
          type: [integer, "null"]
          description: |
            Remaining vertex capacity before the configured limit, or null if unlimited.
            With `cluster-forest` the engine's own capacity can be reached first (see
            `max_nodes` in `GET /v1/info`).
        remaining_edges:
          type: [integer, "null"]
          description: |
            Remaining edge capacity before the configured limit, or null if unlimited.
            With `cluster-forest` the engine's own capacity can be reached first.
        state_version:
          type: string
          pattern: '^[0-9]+$'
          description: Decimal string monotonic version counter incremented on effective mutations.
        instance_id:
          type: string
          description: Source-managed mode only. Current process instance ID.
        generation:
          $ref: '#/components/schemas/FeederU64'
          description: |
            Source-managed mode only. Published generation as a JSON integer that can exceed
            2^53; clients must parse it losslessly. The `X-Knotrel-Generation` header carries
            the same value as a decimal string in both modes.
        source_position:
          type: string
          description: |
            Source-managed mode only, and only once a source position exists. Raw (not
            percent-encoded) applied source position.
        sync_status:
          $ref: '#/components/schemas/FeederSyncStatus'
        source_id:
          type: string
          description: |
            Source-managed mode only, once a generation exists (experimental, new in 1.3): the
            source ID of the current generation. With `source_epoch`, `source_position` and
            `applied_delivery_sequence`, a feeder reads it after registering its session to
            decide whether to resume with events or replace the graph.
        source_epoch:
          type: string
          description: |
            Source-managed mode only, once a generation exists (experimental, new in 1.3): the
            source epoch of the current generation.
        applied_delivery_sequence:
          $ref: '#/components/schemas/FeederU64'
          description: |
            Source-managed mode only, once a generation exists (experimental, new in 1.3): the
            last applied delivery sequence of the current generation, `0` right after an import.
            The next event carries this value plus one.
        restored_snapshot:
          description: |
            Source-managed mode only, once a generation exists (experimental, new in 1.3): the
            snapshot the current generation was restored from at startup, or `null` when it was
            published by an import. `generation` and `delivery_sequence` are those of the process
            that took the snapshot, for information only: the restored generation counts from 1
            and its delivery sequence from 0.
          oneOf:
            - type: 'null'
            - type: object
              required: [snapshot_id, generation, delivery_sequence]
              additionalProperties: false
              properties:
                snapshot_id:
                  type: string
                  pattern: '^[0-9]+$'
                generation:
                  $ref: '#/components/schemas/FeederU64'
                delivery_sequence:
                  $ref: '#/components/schemas/FeederU64'

    SnapshotCreated:
      type: object
      description: A durable snapshot of the default graph (experimental, new in 1.3).
      required:
        - snapshot_id
        - size_bytes
        - generation
        - state_version
        - source_position
        - delivery_sequence
        - node_count
        - edge_count
        - pruned
      properties:
        snapshot_id:
          type: string
          pattern: '^[0-9]+$'
          description: Decimal ID, larger than every earlier snapshot of the directory.
        size_bytes:
          type: integer
          minimum: 0
          description: Size of the snapshot file in bytes.
        generation:
          $ref: '#/components/schemas/FeederU64'
          description: Generation of the graph at the snapshot point.
        state_version:
          type: string
          pattern: '^[0-9]+$'
          description: State version of the graph at the snapshot point.
        source_position:
          type: [string, "null"]
          description: Applied source position at the snapshot point; a restore resumes after it.
        delivery_sequence:
          $ref: '#/components/schemas/FeederU64'
          description: Applied delivery sequence at the snapshot point (information only).
        node_count:
          type: integer
          minimum: 0
          description: Registered nodes in the snapshot.
        edge_count:
          type: integer
          minimum: 0
          description: Registered edges in the snapshot.
        pruned:
          type: integer
          minimum: 0
          description: Older snapshots removed by retention after this one became durable.

    ActiveNodeCount:
      type: integer
      minimum: 0
      description: Lifecycle support only. Registered nodes whose flag is active.

    EnabledEdgeCount:
      type: integer
      minimum: 0
      description: Lifecycle support only. Registered edges whose flag is enabled, effective or not.

    EffectiveEdgeCount:
      type: integer
      minimum: 0
      description: Lifecycle support only. Edges that are enabled and whose endpoints are both active.

    # Inspection payloads (GET /v1/nodes, /v1/nodes/{node}, /v1/nodes/{node}/edges, /v1/edges).

    InspectedNode:
      type: object
      required: [node, active, degree]
      properties:
        node:
          $ref: '#/components/schemas/NodeId'
        active:
          type: boolean
          description: The node's flag; always `true` without lifecycle support.
        degree:
          type: [integer, "null"]
          minimum: 0
          description: |
            Registered incident edges (enabled or not); `null` for `ett` and `hdt`, and for
            `cluster-forest` without lifecycle support.

    NodePage:
      type: object
      required: [nodes, next_after]
      properties:
        nodes:
          type: array
          maxItems: 1000
          items:
            $ref: '#/components/schemas/InspectedNode'
        next_after:
          description: Cursor of the next page (`after`); `null` when the traversal is complete.
          oneOf:
            - $ref: '#/components/schemas/NodeId'
            - type: "null"

    IncidentEdge:
      type: object
      required: [neighbor, enabled, effective]
      properties:
        neighbor:
          $ref: '#/components/schemas/NodeId'
        enabled:
          type: boolean
          description: The edge's own flag (desired state).
        effective:
          type: boolean
          description: Enabled with both endpoints active; participates in connectivity.

    IncidentEdgePage:
      type: object
      required: [node, edges, next_after]
      properties:
        node:
          $ref: '#/components/schemas/InspectedNode'
        edges:
          type: array
          maxItems: 1000
          items:
            $ref: '#/components/schemas/IncidentEdge'
        next_after:
          description: Last neighbor examined, the cursor of the next page; `null` when complete.
          oneOf:
            - $ref: '#/components/schemas/NodeId'
            - type: "null"

    InspectedEdge:
      type: object
      required: [source, target, enabled, effective]
      properties:
        source:
          $ref: '#/components/schemas/NodeId'
        target:
          $ref: '#/components/schemas/NodeId'
        enabled:
          type: boolean
        effective:
          type: boolean

    EdgePage:
      type: object
      required: [edges, next_after_source, next_after_target]
      properties:
        edges:
          type: array
          maxItems: 1000
          items:
            $ref: '#/components/schemas/InspectedEdge'
        next_after_source:
          description: Resume position (`after_source`); `null` when the traversal is complete.
          oneOf:
            - $ref: '#/components/schemas/NodeId'
            - type: "null"
        next_after_target:
          description: Resume position inside `next_after_source` (`after_target`), or `null`.
          oneOf:
            - $ref: '#/components/schemas/NodeId'
            - type: "null"

    # Feeder payloads; operational recovery details are in integration-contract.md.

    ImportNode:
      description: |
        One `nodes` entry of `POST /v1/feeder/import`: a node ID string (active), or an
        object with both members required. The object form requires lifecycle support even
        when `active` is `true`; otherwise the import is rejected with 409
        `topology_lifecycle_disabled`.
      oneOf:
        - $ref: '#/components/schemas/NodeId'
        - type: object
          required:
            - node
            - active
          additionalProperties: false
          properties:
            node:
              $ref: '#/components/schemas/NodeId'
            active:
              type: boolean

    ImportEdge:
      type: object
      description: |
        One `edges` entry of `POST /v1/feeder/import`. Missing endpoints are registered
        active. `enabled` (default `true`) requires lifecycle support even when `true`.
      required:
        - source
        - target
      additionalProperties: false
      properties:
        source:
          $ref: '#/components/schemas/NodeId'
        target:
          $ref: '#/components/schemas/NodeId'
        enabled:
          type: boolean
          default: true

    ImportRequest:
      type: object
      description: |
        Body of `POST /v1/feeder/import`. It must carry the complete registered topology,
        including isolated and inactive nodes and disabled edges. Repeated entries must
        agree; a conflicting flag is 422 `invalid_node` or `invalid_edge`.
      required:
        - mode
        - instance_id
        - graph_id
        - source_id
        - source_epoch
        - source_position
        - feeder_session_id
        - feeder_epoch
        - nodes
        - edges
      additionalProperties: false
      properties:
        mode:
          type: string
          enum: [create_only, replace]
        instance_id:
          type: string
        graph_id:
          type: string
          const: default
          description: Any other value is refused with 400 `invalid_graph_id`, not 422.
        source_id:
          type: string
        source_epoch:
          type: string
        source_position:
          type: string
          minLength: 1
          maxLength: 256
          description: Opaque source cursor of the imported snapshot, 1 to 256 bytes of UTF-8. The limit counts UTF-8 bytes, which the server enforces; `minLength`/`maxLength` count characters, so a multibyte string can be refused (422 `invalid_request`) below the character limit.
        feeder_session_id:
          type: string
        feeder_epoch:
          $ref: '#/components/schemas/FeederU64'
        nodes:
          type: array
          items:
            $ref: '#/components/schemas/ImportNode'
        edges:
          type: array
          items:
            $ref: '#/components/schemas/ImportEdge'

    ImportResponse:
      type: object
      description: Successful import publication (`201 Created`).
      required:
        - result
        - instance_id
        - graph_id
        - generation
        - state_version
        - node_count
        - edge_count
        - source_position
        - status
      properties:
        result:
          type: string
          enum: [published]
        instance_id:
          type: string
        graph_id:
          type: string
          const: default
        generation:
          allOf:
          - $ref: '#/components/schemas/FeederU64'
          - minimum: 1
        state_version:
          type: string
          pattern: '^[0-9]+$'
        node_count:
          type: integer
          minimum: 0
          description: Registered nodes.
        edge_count:
          type: integer
          minimum: 0
          description: Registered edges.
        active_node_count:
          $ref: '#/components/schemas/ActiveNodeCount'
        enabled_edge_count:
          $ref: '#/components/schemas/EnabledEdgeCount'
        effective_edge_count:
          $ref: '#/components/schemas/EffectiveEdgeCount'
        source_position:
          type: string
        status:
          type: string
          enum: [uninitialized, loading, catching_up, ready, stale, desynchronized]

    FeederEvent:
      type: object
      description: |
        One event of `POST /v1/feeder/events`. Required and forbidden operands by `op`:
        `add_node` needs `node`; `link` and `cut` need `source` and `target`; `progress`
        has no operand; `set_node_active` needs `node` and `active`; `set_edge_enabled`
        needs `source`, `target` and `enabled`; `remove_node` needs `node`. Any other
        operand is forbidden (422 `invalid_request`), so `active` and `enabled` are
        rejected on `add_node`, `link`, `cut` and `progress` whatever the setting. The three
        lifecycle operations require lifecycle support; otherwise the whole request is
        rejected with 409 `topology_lifecycle_disabled`.
      required:
        - event_id
        - delivery_sequence
        - prev_delivery_sequence
        - source_position
        - prev_source_position
        - op
      additionalProperties: false
      properties:
        event_id:
          type: string
          maxLength: 64
          description: At most 64 bytes of UTF-8 (no minimum). The limit counts UTF-8 bytes, which the server enforces; `minLength`/`maxLength` count characters, so a multibyte string can be refused (422 `invalid_request`) below the character limit.
        delivery_sequence:
          type: integer
          minimum: 0
        prev_delivery_sequence:
          type: integer
          minimum: 0
        source_position:
          type: string
          minLength: 1
          maxLength: 256
          description: 1 to 256 bytes of UTF-8. The limit counts UTF-8 bytes, which the server enforces; `minLength`/`maxLength` count characters, so a multibyte string can be refused (422 `invalid_request`) below the character limit.
        prev_source_position:
          type: string
          minLength: 1
          maxLength: 256
          description: 1 to 256 bytes of UTF-8. The limit counts UTF-8 bytes, which the server enforces; `minLength`/`maxLength` count characters, so a multibyte string can be refused (422 `invalid_request`) below the character limit.
        op:
          type: string
          enum: [add_node, link, cut, progress, set_node_active, set_edge_enabled, remove_node]
        node:
          $ref: '#/components/schemas/NodeId'
        source:
          $ref: '#/components/schemas/NodeId'
        target:
          $ref: '#/components/schemas/NodeId'
        active:
          type: boolean
          description: Required on `set_node_active`; forbidden on every other operation.
        enabled:
          type: boolean
          description: Required on `set_edge_enabled`; forbidden on every other operation.

    FeederU64:
      type: integer
      minimum: 0
      maximum: 18446744073709551615
    FeederSyncStatus:
      type: string
      enum:
      - uninitialized
      - loading
      - catching_up
      - ready
      - stale
      - desynchronized
    SessionRequest:
      type: object
      required:
      - instance_id
      - feeder_session_id
      - feeder_epoch
      - lease_duration_ms
      properties:
        instance_id:
          type: string
        feeder_session_id:
          type: string
        feeder_epoch:
          $ref: '#/components/schemas/FeederU64'
        lease_duration_ms:
          type: integer
          minimum: 1000
          maximum: 60000
          description: A value outside the range is refused with 400 `invalid_lease_duration`, not 422.
      additionalProperties: false
    HeartbeatRequest:
      type: object
      required:
      - instance_id
      - feeder_session_id
      - feeder_epoch
      properties:
        instance_id:
          type: string
        feeder_session_id:
          type: string
        feeder_epoch:
          $ref: '#/components/schemas/FeederU64'
      additionalProperties: false
    SessionResponse:
      type: object
      required:
      - result
      - instance_id
      - feeder_session_id
      - feeder_epoch
      - lease_duration_ms
      - generation
      - applied_delivery_sequence
      - applied_source_position
      - status
      properties:
        result:
          type: string
          enum:
          - session_acquired
        instance_id:
          type: string
        feeder_session_id:
          type: string
        feeder_epoch:
          $ref: '#/components/schemas/FeederU64'
        lease_duration_ms:
          $ref: '#/components/schemas/FeederU64'
        generation:
          $ref: '#/components/schemas/FeederU64'
        applied_delivery_sequence:
          $ref: '#/components/schemas/FeederU64'
        applied_source_position:
          type:
          - string
          - 'null'
        status:
          $ref: '#/components/schemas/FeederSyncStatus'
    HeartbeatResponse:
      type: object
      required:
      - result
      - instance_id
      - feeder_session_id
      - feeder_epoch
      - lease_expires_in_ms
      - status
      properties:
        result:
          type: string
          enum:
          - heartbeat_acknowledged
        instance_id:
          type: string
        feeder_session_id:
          type: string
        feeder_epoch:
          $ref: '#/components/schemas/FeederU64'
        lease_expires_in_ms:
          $ref: '#/components/schemas/FeederU64'
        status:
          $ref: '#/components/schemas/FeederSyncStatus'
    FeederEventsRequest:
      type: object
      required:
      - instance_id
      - feeder_session_id
      - feeder_epoch
      - graph_id
      - generation
      - source_id
      - source_epoch
      - events
      properties:
        instance_id:
          type: string
        feeder_session_id:
          type: string
        feeder_epoch:
          $ref: '#/components/schemas/FeederU64'
        graph_id:
          type: string
          const: default
        generation:
          $ref: '#/components/schemas/FeederU64'
        source_id:
          type: string
        source_epoch:
          type: string
        events:
          type: array
          minItems: 1
          maxItems: 1024
          items:
            $ref: '#/components/schemas/FeederEvent'
      additionalProperties: false
    FeederEventsResponse:
      type: object
      required:
      - result
      - instance_id
      - generation
      - applied_delivery_sequence
      - applied_source_position
      - state_version
      - events_applied
      properties:
        result:
          type: string
          enum:
          - applied
        instance_id:
          type: string
        generation:
          $ref: '#/components/schemas/FeederU64'
        applied_delivery_sequence:
          $ref: '#/components/schemas/FeederU64'
        applied_source_position:
          type: string
        state_version:
          type: string
          pattern: ^[0-9]+$
        events_applied:
          type: integer
          minimum: 0
    FeederDuplicateResponse:
      type: object
      required:
      - result
      - status
      - instance_id
      - generation
      - event_id
      - delivery_sequence
      - historical_outcome
      - current_applied_delivery_sequence
      - current_applied_source_position
      - current_state_version
      properties:
        result:
          type: string
          enum:
          - duplicate
        status:
          type: string
          enum:
          - already_applied
        instance_id:
          type: string
        generation:
          $ref: '#/components/schemas/FeederU64'
        event_id:
          type: string
        delivery_sequence:
          $ref: '#/components/schemas/FeederU64'
        historical_outcome:
          type: object
          required:
          - changed
          properties:
            changed:
              type: boolean
        current_applied_delivery_sequence:
          $ref: '#/components/schemas/FeederU64'
        current_applied_source_position:
          type: string
        current_state_version:
          type: string
          pattern: ^[0-9]+$
    PartialBatchFailure:
      type: object
      required:
      - result
      - code
      - message
      - instance_id
      - generation
      - applied_delivery_sequence
      - applied_source_position
      - state_version
      - failed_batch_index
      - failed_delivery_sequence
      - failed_event_id
      - error
      properties:
        result:
          type: string
          enum:
          - partial_failure
        code:
          $ref: '#/components/schemas/ErrorCode'
        message:
          type: string
        instance_id:
          type: string
        generation:
          $ref: '#/components/schemas/FeederU64'
        applied_delivery_sequence:
          $ref: '#/components/schemas/FeederU64'
        applied_source_position:
          type: string
        state_version:
          type: string
          pattern: ^[0-9]+$
        failed_batch_index:
          type: integer
          minimum: 0
        failed_delivery_sequence:
          $ref: '#/components/schemas/FeederU64'
        failed_event_id:
          type: string
        error:
          type: object
          required:
          - code
          - message
          properties:
            code:
              $ref: '#/components/schemas/ErrorCode'
            message:
              type: string
    GapRequest:
      type: object
      required:
      - instance_id
      - feeder_session_id
      - feeder_epoch
      - graph_id
      - generation
      - failed_delivery_sequence
      properties:
        instance_id:
          type: string
        feeder_session_id:
          type: string
        feeder_epoch:
          $ref: '#/components/schemas/FeederU64'
        graph_id:
          type: string
          const: default
        generation:
          $ref: '#/components/schemas/FeederU64'
        failed_delivery_sequence:
          $ref: '#/components/schemas/FeederU64'
        reason:
          type:
          - string
          - 'null'
      additionalProperties: false
    GapResponse:
      type: object
      required:
      - result
      - instance_id
      - generation
      - status
      - action_required
      properties:
        result:
          type: string
          enum:
          - gap_acknowledged
        instance_id:
          type: string
        generation:
          $ref: '#/components/schemas/FeederU64'
        status:
          type: string
          enum:
          - desynchronized
        action_required:
          type: string
          enum:
          - full_rebuild_required
    BarrierRequest:
      type: object
      required:
      - instance_id
      - feeder_session_id
      - feeder_epoch
      - graph_id
      - generation
      - barrier_delivery_sequence
      properties:
        instance_id:
          type: string
        feeder_session_id:
          type: string
        feeder_epoch:
          $ref: '#/components/schemas/FeederU64'
        graph_id:
          type: string
          const: default
        generation:
          $ref: '#/components/schemas/FeederU64'
        barrier_delivery_sequence:
          $ref: '#/components/schemas/FeederU64'
        barrier_source_position:
          type:
          - string
          - 'null'
          minLength: 1
          maxLength: 256
          description: Optional; when absent or null, only the delivery sequence is validated. When present, 1 to 256 bytes of UTF-8 and must equal the applied source position. The limit counts UTF-8 bytes, which the server enforces; `minLength`/`maxLength` count characters, so a multibyte string can be refused (422 `invalid_request`) below the character limit.
      additionalProperties: false
    BarrierResponse:
      type: object
      required:
      - result
      - instance_id
      - graph_id
      - generation
      - state_version
      - applied_source_position
      - status
      properties:
        result:
          type: string
          enum:
          - synchronized
          - already_synchronized
        instance_id:
          type: string
        graph_id:
          type: string
          const: default
        generation:
          $ref: '#/components/schemas/FeederU64'
        state_version:
          type: string
          pattern: ^[0-9]+$
        applied_source_position:
          type: string
        status:
          type: string
          enum:
          - ready
