Skip to content

The query surface (OSL-SQL)

POST /osl/query is the single consumption endpoint. Structured analytics, metrics, governed vector retrieval, graph traversal and document analytics are all expressed here — you don’t learn a surface per data shape to read a domain.

POST /osl/query
Authorization: Bearer <jwt> # attested delegation chain, see Authentication
Content-Type: application/json

The body is one of three mutually-exclusive shapes (mixing them is 400 E0513); all three go through the same governed seam and share one request_id:

Body What it is
{ "osql": "…" } OSL-SQL — the semantic SQL dialect (the canonical surface)
{ "sql": "…" } A raw read-only SELECT over the tenant allowlist (the SQL slice)
{ "metrics": […], "group_by": […], … } MetricFlow-style metrics query (single-model simple metrics today)

Two optional booleans modify an osql body: explain: true validates and lowers without executing (below), and allow_async: false refuses a query that would otherwise run as a job (413 E0519).

osql is a semantic SQL dialect. It names only semantic objects — osl.entities.<model> and declared columns, osl.documents.<facet>, or the table functions RETRIEVE(...) / TRAVERSE(...) / CLASSIFY(...) / SYNTHESISE(...). It never names a physical table or a raw column.

The engine parses osql (via sqlglot, trino dialect) and lowers it to a closed operator IR — the deterministic ladder the governance model enforces over. Lowering is total and default-deny: any construct that does not lower to a known IR node is refused.

lower() classifies each query into exactly one form and validates its grammar. The five core forms:

SELECT segment, COUNT(*) AS n
FROM osl.entities.Customer
WHERE country IN ('ES','FR','DE')
GROUP BY segment
ORDER BY n DESC
LIMIT 100

Lowers to to_trino() → the governed SQL seam. Joins between structured entities are allowed only as a sealed-key equijoin (see below).

On top of these, the reference engine serves the population-analytics forms of RFC 0006 Draft: document aggregates over osl.documents.<facet> and exhaustive jobs (CLASSIFY / SYNTHESISE).

The only cross-relational node is an equijoin whose ON is a scalar equality on a sealed entity key on both legs — for a JointEntity leg the ON must use its declared primary_key, and the correlated facet field must be a declared, scalar-indexed metadata field. Any other JOIN … ON → 400 E0514.

There is no syntax that hands a second relational argument to a similarity or LLM operator — a relation×relation semantic join at query time (the non-goal R3) is a structural property of the grammar, not a blocklist to maintain. The full-text MATCHES predicate is a set inside one relation’s WHERE, never a join condition.

X JOIN RETRIEVE(...) ON X.k = R.k is not a relational join of two physical tables. It runs as:

  1. RETRIEVE (governed) → passages, each carrying its denormalized key.
  2. Cleartext gate → the key values, or refuse (403 E0515).
  3. Structured prefilter: … WHERE k IN (<keys>) → to_trino → governed SQL (the IN-list is built with sqlglot literal conversion — injection-safe).
  4. In-cell hash join on the sealed key, projecting each leg’s columns.

Questions about a population of documents — “how many notices last quarter, by reason?” — are answered by osl.documents.<facet>: the facet at document grain, one row per visible document, aggregated exactly over the subject’s whole visible subset.

SELECT reason_code, gateway, count(*) AS notices
FROM osl.documents.dispute_notices
WHERE notified_at BETWEEN '2026-07-01' AND '2026-09-30T23:59:59'
GROUP BY reason_code, gateway
ORDER BY notices DESC

The response is shape: "facet_aggregate", with a population block (documents and chunks visible to this subject, with the Lance version read) and a validity block (exactness, coverage, derived_fields_used, policy_ids, capped: false).

  • Aggregate-only. Grouping keys plus count, count(DISTINCT …), sum, avg, min, max (and round, coalesce, lower, upper, cast, date_trunc). count(*) counts documents. A bare row, or text / embedding / score / cite / chunk_id, is E0511 — individual documents are evidence and go through RETRIEVE.
  • Cleartext columns only. Grouping, filtering or aggregating a column masked or withheld for the subject is refused with E0518 — never answered with *** buckets, which would leak cardinality. A string group key must be a declared categorical dimension (indexed: scalar, or a closed-vocabulary derivation).
  • Exact or nothing. No sampling. Above the synchronous budget the same query becomes an exhaustive aggregate job (202), or 413 E0519 when it cannot run as a job. A denied facet is 403 E2101, never a population of zero.
  • Joins — [LEFT] JOIN osl.entities.<model> on a sealed key (E0514 otherwise); LEFT JOIN … WHERE t.<key> IS NULL means “no matching row visible to this subject”. The entity side must be unique in the join key among the subject’s visible rows, or the query is refused with 409 E0538 (only shapes whose answer cannot depend on which duplicate is chosen are served over a non-unique key).
  • GROUP BY over RETRIEVE stays E0511 — top-k is evidence, not a population.

Every RETRIEVE and cross-modal response also carries population (documents visible to the subject under the same WHERE) and documents_returned, so a client can present “5 of 41 873 visible documents” instead of generalising from the top-k.

CLASSIFY and SYNTHESISE read every visible document of a facet:

SELECT * FROM CLASSIFY(facet => 'dispute_notices',
labels => ('fraud', 'service_not_received', 'other'),
group_by => 'gateway')
WHERE notified_at >= '2026-07-01'

They — and a document aggregate above the synchronous budget — are answered 202 with shape: "job" and a job_id. Poll GET /osl/jobs/{job_id} and read GET /osl/jobs/{job_id}/result once status is succeeded. A job pins the Lance version and the composed policy snapshot at submission, re-checks the subject’s policy while it runs, and is visible only to the submitting subject (anyone else gets 404 E0525). Results expire after a configurable retention (7 days by default).

{"osql": "…", "explain": true} parses and lowers the query through the same lower() boundary as execution, then returns the plan without executing it: no allowlist fetch, no policy composition, no Trino or Lance read, no rows. It accepts exactly what execution would accept and refuses the rest with the same E0511/E0512/E0514.

{
"request_id": "01HV...",
"explain": true,
"shape": "retrieve",
"plan": { "facets": ["transcripts"], "retrieve": { "facet": "transcripts", "top_k": 3, "projection_ops": [] }, "columns": ["text"], "…": "…" },
"normalized_osql": null
}

The plan is data-free — names, output columns, aggregate functions and key counts, never key literals or the RETRIEVE query text — so an explain body can be logged or relayed safely. explain: true with {sql} or MetricFlow fields is refused with 400 E0513.

Responses are shape-tagged (structural, retrieve, traverse, joint, joint_relation, cross_modal_join, facet_aggregate, document_join, job) under the request’s request_id. An executed query also carries a data-free provenance object — datasets_read, sql_hash, columns_read, output_columns, filter_columns — so a caller can explain an answer without reading the audit ledger. Joint and cross-modal responses declare consistency.mode: "eventual" with the observed physical version per source.

Temporal literals are ISO-8601 strings on every body (WHERE fecha >= '2026-09-01', '2026-09-01T10:00:00+02:00'): the governed seam casts them to the column’s physical date/timestamp type. A non-ISO string compared with a temporal column is 400 E0511.

In the RETRIEVE form, <op>(col) in the SELECT is a projection operator (RFC 0004). They are unary maps — never a join.

Class Operators Runs If missing
Encoder (deterministic) SIMILARITY, CLASSIFY, TAG, RANK, DEDUP, OUTLIER, CLUSTER On embeddings already in the chunk —
Decoder (inference) needs LLM EXTRACT, SUMMARIZE, SCORE, GENERATE, COMPLETE An LLM backend 503 E0521

classify(col, …) in a RETRIEVE select list is this projection over the top-k passages; CLASSIFY(...) in FROM is the exhaustive job. Position decides.

{ "sql": "<SELECT>" } is a read-only SELECT validated against the tenant allowlist with the policy enforcement point applied (row filters + projection from the composed snapshot). { "metrics": …, "group_by": … } follows MetricFlow semantics. Both share the same governed seam as osql.

Code Meaning
200 Success
202 Accepted as a job (shape: "job")
400 Out-of-grammar (E0511), body mixes shapes (E0513), non-sealed-key JOIN (E0514), masked column in an analytic or order (E0518), invalid cursor (E0530), empty sql (E0246)
403 PDP deny (E2101/E2102, E2105 no grant), cross-modal key not cleartext (E0515), object not declared / outside allowlist (E0512)
404 Unknown job — or another subject’s (E0525)
409 Stale cursor (E0531), pinned version not servable (E0520), non-unique document-join key (E0538)
413 Population above the synchronous budget and not runnable as a job (E0519)
422 Valid but unresolvable — e.g. a MetricFlow shape not implemented yet (E1xxx)
429 Policy reading window exhausted (E0532, with Retry-After)
502 Trino execution failure (E0510), analytic read not completed exactly (E0523)
503 PDP snapshot missing (E2001, fail-closed), no LLM backend (E0521), no job store (E0524), reading-window ledger unavailable (E0534)

See Errors & status codes for the full envelope.