OpenMetadata icon indicating copy to clipboard operation
OpenMetadata copied to clipboard

Add permissioned read-only SPARQL execution for the 2.1 graph agent tool

Open fmcardoso opened this issue 2 months ago • 0 comments

Parent epic and companion work

Parent epic: https://github.com/open-metadata/ai-platform/issues/224

  • Agent implementation: https://github.com/open-metadata/ai-platform/issues/1299
  • Architecture/design PR: https://github.com/open-metadata/ai-platform/pull/1310
  • Parallel asset-level authorization: https://github.com/open-metadata/OpenMetadata/issues/33224 (not a blocker for this ticket)
  • Target: 2.1

Problem and goal

The model-authored SPARQL graph tool needs a permissioned, read-only, bounded server execution surface for lineage, relationship filtering, and traversal aggregation. The existing POST /api/v1/rdf/sparql endpoint is an administrator surface; the agent must not bypass it with elevated credentials or by dropping caller impersonation.

Implement the OpenMetadata companion server surface, preserving existing administrator/UI behavior. This ticket implements server execution and its contract tests, not the ai-platform tool or an LLM query-generation endpoint.

Asset-level rule-based authorization remains parallel work under #33224. Initial acceptance requires authentication, endpoint permission, validated caller propagation, and documentation of the exposed dataset. It does not require asset-level mixed-access filtering or leakage prevention, and must not claim those guarantees.

Reviewed design baseline

Read the full proposal before implementation; the links are pinned to the reviewed ai-platform commit:

The proposal reflects source inspection on 2026-09-15. Recheck paths, capabilities, and ceilings against the implementation branch. Finalize remaining wire-contract choices with the companion owner and record them using OpenMetadata's decision-record conventions before generating schemas. The proposed API is not an already deployed contract.

Scope

1. Separate permissioned execution endpoint

Proposed surface:

POST /api/v1/rdf/sparql/agent
Content-Type: application/json
Accept: application/json

Request: a declared AgentSparqlQuery containing only query (SPARQL text). No body fields for identity, credentials, arbitrary dataset/graph URI, or protective-limit overrides. Explicit SPARQL LIMIT/OFFSET remain query semantics, subject to server maxima.

Authorize a dedicated RDF-query operation. Do not reuse authorizeAdmin, and do not substitute VIEW_ALL without an explicit operation/policy mapping. Keep the existing admin endpoint backward-compatible.

2. Effective caller and audit identity

CAIP sends a bot JWT in Authorization and the requested user in X-Impersonate-User.

  • Validate impersonation using existing server security rules before authorization/execution.
  • Use the validated effective caller for permissions and per-user execution concurrency.
  • Retain both authenticated service actor and effective caller in a structured server audit log event; persisted read-audit records are outside v1 scope.
  • Reject invalid or untrusted impersonation; never fall back to the bot's privileges after a failed user check.
  • Without an impersonation header, the authenticated actor is the effective caller and must independently have the endpoint permission.

3. Reuse execution infrastructure and constrain query forms

Reuse RdfSparqlService, SparqlFederationGuard, SparqlQueryExecutionGuard, and SparqlQueryLimits; do not create a second executor.

Accept SELECT, including aggregates and supported subqueries. Reject ASK, CONSTRUCT, DESCRIBE, UPDATE, SERVICE/federation, FROM, FROM NAMED, and constant/variable GRAPH. Inspect the parsed query tree, including nested forms, rather than using regexes. Execute the validated, bounded query.

The server selects the configured RDF dataset/default graph and forces inference to none. No persona or asset-level filtering is provided. Reuse existing readiness checks before execution and before success; rebuilding, degraded, or unknown state returns PROJECTION_NOT_READY. No blue/green-aware availability, generation pinning, snapshot guarantee, or vocabulary-compatibility signal is required.

4. Typed results, limits, and completeness

Publish declared request/response/error schemas and generated models. Return SPARQL SELECT bindings preserving URI, blank-node, literal datatype/language, and unbound-value semantics, plus completeness and effective-limit metadata. effectiveScope, projectionVersion, and projectionState are deliberately omitted; the client must not require them.

  • A successful empty binding set is distinct from failure.
  • Completeness is relative to the submitted query, not a claim that its explicit top-N covers every matching entity.
  • Preserve explicit LIMIT, OFFSET, and limits inside aggregate-producing subqueries.
  • For an outer result without an explicit limit, use an overflow probe: exactly 1,000 rows is complete only if there is no 1,001st row; overflow returns valid JSON with TRUNCATED / SERVER_ROW_LIMIT.
  • Do not alter subquery/aggregate semantics to probe. If completeness cannot be established without changing semantics, return UNKNOWN rather than claiming completeness.
  • Reject explicit limits above the server maximum. Apply protective outer-result limits after OFFSET.
  • If the serialized response exceeds the output-byte ceiling, return a structured error before committing headers, without a partial result body or cut-off JSON. This does not bound serialization or backend-result memory; storage streaming is outside v1 scope.
  • Server execution completeness is separate from later ai-platform model-context rendering omissions.

Recheck and retain existing ceilings unless measurement and a decision record justify changing them: 100,000 query characters, 1,000 default outer-result rows, 10,000 maximum explicit/protective rows, 10 MiB output, 30 seconds, eight global concurrent executions, and two per effective-caller hash stripe (existing guard behavior: distinct users can collide). Row limits do not bound aggregate input work; execution guards remain necessary.

5. Stable failure contract

Return safe structured errors such as {code, message, requestId}. Distinguish malformed queries, prohibited forms/graph selection/federation, excessive explicit limits, authentication, endpoint permission, impersonation, capacity, output-size exhaustion, timeout, unavailable repository, projection-not-ready, and unexpected backend failure.

Use the proposed code/HTTP mapping in the linked server proposal as the baseline. Shared HTTP statuses must not collapse distinct machine-readable categories. Do not expose credentials or unsafe backend/query internals in diagnostics. Row-truncated results are valid HTTP 200 responses with explicit completeness metadata.

Acceptance criteria

  • [ ] Final request/response/error schemas and OpenAPI contract are published for KnowledgeGraphApi.executeQuery in ai-platform.
  • [ ] An explicitly permitted ordinary caller can execute the new operation; unauthorized effective callers are rejected.
  • [ ] Actual bot-JWT-plus-X-Impersonate-User tests verify effective-user authorization, service/effective-user audit attribution, and untrusted impersonation rejection. Guard/service tests verify effective-user quota-key forwarding, shared quotas for the same user, and independence across distinct stripes.
  • [ ] Existing admin/UI RDF behavior has regression coverage and remains backward-compatible.
  • [ ] Parsed-query tests reject unsupported query forms, federation, FROM/FROM NAMED, and constant/variable GRAPH, including nested forms.
  • [ ] Known-fixture tests cover empty results, joins, aggregates, and typed RDF bindings.
  • [ ] Boundary tests cover explicit LIMIT 10, exactly 1,000 versus 1,001 unbounded outer rows, limits above the maximum, OFFSET, subquery/aggregate limits, and output-byte exhaustion without partial JSON.
  • [ ] Timeout, capacity, unavailable/not-ready projection, repository failures, and stable error-code behavior are covered.
  • [ ] Exposed dataset, inference/projection behavior, endpoint permission, and absence of asset-level authorization are documented honestly.
  • [ ] Mixed-access asset/path/aggregate leakage tests remain conditional on #33224 and are outside this ticket's initial acceptance criteria.
  • [ ] The final wire contract and authorization limitation ship in an OpenMetadata decision record; deviations from the reviewed proposal are reconciled with the companion owner.
  • [ ] Companion draft PR links this issue, ai-platform #1299, epic #224, and design PR #1310, and reports exact verification results and any checks not run.

Implementation sequence

  1. Read OpenMetadata's own contributor instructions; recheck the existing execution/security implementation.
  2. Record the reconciled cross-repo contract, explicit operation/policy mapping, fixed scope, and conservative readiness policy in the server ADR.
  3. Add schemas/models, the endpoint, shared execution integration, and completeness/error handling.
  4. Add unit, integration, and backward-compatibility tests; run the repository's required gates.
  5. Open a companion draft PR and publish the contract for agent integration. Human merge only.

Agent scaffolding and offline evaluation can proceed in parallel; ordinary-user production enablement requires this permissioned server surface. Broad HybridSearch comparisons and model-query generation evaluation belong to the ai-platform work, not this server ticket.

Initial-contract amendment (2026-09-16)

Implementation PR: https://github.com/open-metadata/OpenMetadata/pull/33428. The server ADR supersedes the pinned original proposal where they differ; the requirements above incorporate those changes. ExecuteSparqlQuery requires an explicitly named allow operation for non-admins; wildcard denies still apply. Existing Impersonate semantics are unchanged. Asset-level RBAC remains parallel, not a blocker.

The RDF test profile now builds the supported repository Fuseki image rather than the stock image pin; production Fuseki configuration is unchanged. Verification reports 17/17 endpoint ITs and 1,609/1,609 unit tests, with one baseline-reproduced regression error, not a green regression lane. See the commands, baseline SHA, qualifications, and evidence. Full implementation review remains required; acceptance boxes are intentionally not marked complete by this amendment.

fmcardoso avatar Sep 16 '26 07:09 fmcardoso