Waratah query library API (server contract)
Server-side HTTP contract for the console Query library’s server queries section: a read-only, curated list of SPARQL queries a compute publishes per repository. The workbench loads these entries as ready-to-run starting points; a human runs them immediately. The HTTP client lives in the sibling grevillea repo and is already implemented — this page documents what the engine must serve and how the feature is built internally.
Owning sources: waratah_api/src/query_library.rs (storage and loading
rules), waratah_api/src/routes/query_library.rs (the HTTP handler), and
waratah_bin/src/dev.rs (CLI wiring and the built-in demo entries). The
machine-readable contract is ref/waratah_openapi.yaml (attached as
attachment$waratah_openapi.yaml).
Terminology guard: a saved query is a workbench user’s own query and lives only in that browser’s localStorage — it never touches the server. The query library is the operator-curated list documented here. The UI shows them as two separate sections.
There is no CORS anywhere on this route, same as the rest of the Waratah
surface: proxy /waratah onto the UI origin (or serve the console
same-origin, which is the default).
Enabling
| Flag | Effect |
|---|---|
|
Publishes |
|
With no |
On-disk layout
<queries-dir>/
main/
cities.rq one query per file; id = filename stem
cities.toml optional sidecar: name / description / order
people.rq
Rules, all enforced by waratah_api/src/query_library.rs:
-
Flat directory — no recursion. Hidden files (leading
.) and subdirectories are ignored. -
Extensions are case-sensitive and lowercase-only:
UPPER.RQis skipped with a warning, never published. -
Filenames must be valid UTF-8 — the stem becomes the entry
id, and lossily-folded duplicates would break the per-list id uniqueness the UI’s list keys depend on. Non-UTF-8 filenames are skipped with a warning. -
The optional
<id>.tomlsidecar carriesname,description, andorder(integer). Parsing is strict (deny_unknown_fields): a misspelled key fails the whole request with 500 rather than silently degrading the entry to a derived name. Blankname/descriptioncount as absent. -
nameabsent derives from the stem:_and-become spaces and only the first character is uppercased (rdf4j_stats→Rdf4j stats). -
The directory is re-read on every request. At the intended scale (tens of small files) this is cheap, and edits show up on the next panel refresh without a restart.
Endpoint
GET /waratah/repositories/{id}/queries
{
"queries": [
{
"id": "cities",
"name": "Cities",
"description": "All instances of ex:City with their labels",
"query": "PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#>\n…"
}
]
}
| Field | Required | Rules |
|---|---|---|
|
yes |
Filename stem. Stable across restarts and refetches (it is the UI list
key). Recommended |
|
yes |
Sidecar |
|
no |
Omitted from the JSON when the sidecar does not set one. |
|
yes |
Complete SPARQL 1.1 query text, multi-line, UTF-8. |
Query text is served after stripping a leading UTF-8 BOM and normalizing
CRLF / CR to LF; everything else is verbatim, so an LF file round-trips
byte-for-byte. Success responses carry Content-Type: application/json and
Cache-Control: no-store — the UI re-fetches on every panel open and
manual refresh, and must never see a pinned stale list.
Read-time guards (skip + warn, never fail the endpoint)
One stderr warning per file and reason, at most once per process: query
text over 64 KiB (measured on read through a one-byte-past-the-limit
window, so a file that grows mid-read is still caught and a huge file never
loads whole), empty or whitespace-only content, non-UTF-8 content, a path
that is not a regular file (dangling symlink, FIFO), an orphan sidecar with
no matching <stem>.rq, and case-variant extensions. Entries skip
individually; the rest of the library still serves.
Status codes
| Status | When |
|---|---|
200 |
Library configured for this repository. An empty library — the
repository directory exists and holds no usable |
404 |
Unknown |
500 |
A sidecar failed to parse, or a real query file was unreadable. Loud on purpose: a silent skip would make an operator’s typo look like a missing query. |
501 |
No query library configured in this process — the same convention as ingest (501 = no ingest directory) and the AI services. |
405 |
Any method other than GET or HEAD. The surface is read-only in v1. |
There is no discovery/capability route: absence of the feature is signalled
by 404 / 501 alone, like ingest and cluster. The route is reachable through
the cluster proxy as /cors_proxy/{compute_id}/waratah/… unchanged.
Built-in demo queries
--load-demo (without --queries-dir) publishes three entries defined in
waratah_bin/src/dev.rs (demo_queries), each verified to return rows
over demo_dataset, which now also carries the rdfs:label and
rdfs:subClassOf schema triples the AI-context endpoint demonstrates
against — the library queries read only the original ex: vocabulary and
are unaffected by the extension:
| id | Selects | Shape |
|---|---|---|
|
Every |
single type + attribute pattern |
|
|
single type + attribute pattern |
|
each person’s |
two-attribute join — the AGENTS.md §4.2 planning example |
Inline entries keep declaration order on the wire; the (order, id) sort
of the directory source does not apply to them.
How it works (implementation map)
Two sources resolve through one QueryLibrary::load, so the handler cannot
tell them apart:
-
QueryLibrary::Directory(PathBuf)— the--queries-dircase.loadjoins the repository id onto the root (queries_repo_dirinwaratah_storage/src/layout.rs, the same trust shape asingest_staging_dir: ids reach the join only after the handler checked them against the repository catalog, so path traversal through the URL segment cannot escape the root), lists and sorts the directory, then reads each.rq. -
QueryLibrary::Inline(Arc<[ServerQuery]>)— the demo case, held inAppState.query_librarybehind the same Arc as every other process-lifetime service.
The load pipeline: list entries and sort the paths (so ordering never
depends on filesystem return order) → collect the stems of real .rq
files for orphan-sidecar detection → per entry, validate filename UTF-8,
stat for regular-file-ness, read through the size window, normalize text,
parse the sidecar → collect (order, ServerQuery) pairs → final sort by
(order.unwrap_or(0), id). No HashMap is ever iterated into the response;
two consecutive requests return byte-identical bodies, and there is a test
that pins the exact bytes.
Skip warnings dedupe on (path, reason) in a OnceLock<Mutex<HashSet>>:
one bad file must not print a line on every panel refresh, but a file that
becomes bad in a new way (or after being fixed) warns again. The state
maps to errors through two variants — QueryLibraryNotConfigured (501) and
QueryLibrary(QueryLibraryError) where Missing is 404 and Invalid is
500 (waratah_api/src/error.rs).
Extending it later
Deliberate v1 boundaries, and what each extension would touch:
-
Publish/delete API (
POST/PUT/DELETEon the same path). The natural implementation writes<id>.rq(plus sidecar) into the same{queries_dir}/{repository}directory — the endpoint would pick it up on its next per-request read with zero loader changes. Gated on an auth story first: today the whole/waratahsurface is loopback-trusted, and a write API would let a browser page plant executable query text. -
Parameterised queries — an optional
parametersarray per entry so the UI can prompt for values before running (RDF4J query-variable bindings). Purely additive: the client ignores unknown entry fields, so shipping it is a sidecar/loader extension plus a UI change, not a contract break. -
Per-repository inline libraries —
Inlinecurrently serves the same entries for every repository in the catalog. That is coherent while the catalog ismain-only; if the catalog grows, inline entries need a per-repository map (or a documented fallback rule) to keep the per-repository contract honest. -
Softer sidecar strictness —
deny_unknown_fieldstrades forward compatibility for typo visibility. If the sidecar grows optional fields in the future, the balanced shape is: unknown keys warn and are ignored, wrong-typed known keys still fail with 500. -
A docs note: the Antora page you are reading and
docs/query-library-api.md(the older standalone contract hand-off) describe the same surface; keep both in sync with any behavior change, or fold the markdown file away once no external consumer needs it.