Skip to content
Skills Library
Data & analytics · Tool integration

http-server

/http-server

Run or point an agent at a sparq SPARQL 1.1 Protocol HTTP endpoint (sparq-server) — /sparql query+update over GET/POST (plus the query-only HTTP QUERY method, w3c/sparql-protocol#40, for Oxigraph interop), content negotiation (SELECT/ASK JSON/XML/CSV/TSV; CONSTRUCT/DESCRIBE + Graph Store N-Triples/prefix-Turtle/RDF-XML/JSON-LD — JSON-LD via the default-on jsonld feature), Graph Store read AND write (PUT/POST/DELETE/PATCH on graph resources, RDF/XML + default-on JSON-LD bodies accepted, atomic SPARQL-Update + opt-in Solid N3-Patch on PATCH), EXPLAIN, Prometheus /metrics, WebSocket + SSE subscri

Repository
sparq ↗
Licence
MIT
Last repository change
27.10.2026

Assessment and security

91/ 100Class: good
Format25 / 25
Frontmatter with name and description, valid name, description up to 1,024 characters, name matching the folder.
Discoverability25 / 25
Description explains when to use the skill, has a reasonable length and uses third person.
Content26 / 35
At least 150 words and at most 500 lines, headings, step lists, examples or code.
Hygiene15 / 15
No placeholders such as TODO, no Windows paths, with a licence.
Riskno signals detected in the scan
Files in this package
1
Scripts
0
HTML comments
14
URLs in SKILL.md
132
Deprecation

No signals detected. Repository changed on 27.10.2026, without references to retired models or APIs.

Licence

MIT, open: use and modify while retaining author attribution.

What to check before installing
  • SKILL.md zawiera komentarze HTML (14). Nie widać ich w podglądzie Markdown, a model je czyta.

What it does and when to use it

Run or point an agent at a sparq SPARQL 1.1 Protocol HTTP endpoint (sparq-server) — /sparql query+update over GET/POST (plus the query-only HTTP QUERY method, w3c/sparql-protocol#40, for Oxigraph interop), content negotiation (SELECT/ASK JSON/XML/CSV/TSV; CONSTRUCT/DESCRIBE + Graph Store N-Triples/prefix-Turtle/RDF-XML/JSON-LD — JSON-LD via the default-on jsonld feature), Graph Store read AND write (PUT/POST/DELETE/PATCH on graph resources, RDF/XML + default-on JSON-LD bodies accepted, atomic SPARQL-Update + opt-in Solid N3-Patch on PATCH), EXPLAIN, Prometheus /metrics, WebSocket + SSE subscri

Original author description

Run or point an agent at a sparq SPARQL 1.1 Protocol HTTP endpoint (sparq-server) — /sparql query+update over GET/POST (plus the query-only HTTP QUERY method, w3c/sparql-protocol#40, for Oxigraph interop), content negotiation (SELECT/ASK JSON/XML/CSV/TSV; CONSTRUCT/DESCRIBE + Graph Store N-Triples/prefix-Turtle/RDF-XML/JSON-LD — JSON-LD via the default-on jsonld feature), Graph Store read AND write (PUT/POST/DELETE/PATCH on graph resources, RDF/XML + default-on JSON-LD bodies accepted, atomic SPARQL-Update + opt-in Solid N3-Patch on PATCH), EXPLAIN, Prometheus /metrics, WebSocket + SSE subscri

How it works

  1. Quickstart
  2. Key APIs
  3. Common recipes
  4. Gotchas / feature flags / prerequisites
  5. See also
Original SKILL.md headings · 2,124 lines, 22,706 words
SKILL.md preview
---
name: http-server
description: Run or point an agent at a sparq SPARQL 1.1 Protocol HTTP endpoint (sparq-server) — /sparql query+update over GET/POST (plus the query-only HTTP QUERY method, w3c/sparql-protocol#40, for Oxigraph interop), content negotiation (SELECT/ASK JSON/XML/CSV/TSV; CONSTRUCT/DESCRIBE + Graph Store N-Triples/prefix-Turtle/RDF-XML/JSON-LD — JSON-LD via the default-on jsonld feature), Graph Store read AND write (PUT/POST/DELETE/PATCH on graph resources, RDF/XML + default-on JSON-LD bodies accepted, atomic SPARQL-Update + opt-in Solid N3-Patch on PATCH), EXPLAIN, Prometheus /metrics, WebSocket + SSE subscriptions, opt-in grouped facet counts and prefix completion, and generation-pinned snapshot reads (a Sparq-Generation header + ?generation=N pin in the DEFAULT build, bounded to the ring's concurrency-retention window; opt-in time-travel widens it). Use when starting the server, querying/updating a running endpoint, choosing Accept/Content-Type, or embedding the axum router.
---

# sparq-http-server

`sparq-server` is a W3C-conformant HTTP server (axum/tokio) that exposes the sparq
query engine over a `sparq_core::Graph` — in-memory by default, or **durable on disk**
with `--persist DIR` (updates WAL-fsync'd, survive a restart with no rebuild; see the
"Durability" gotcha). It implements the **SPARQL 1.1 Protocol** (`query` + `update` at
`/sparql`) and the **Graph Store HTTP Protocol** (read + write), with `Accept`-driven
content negotiation, hardening guards, Prometheus `/metrics`, WebSocket + SSE subscriptions,
and opt-in grouped facet counts, prefix completion, time-travel, and GeoSPARQL.

Build with the default-off `response-compression` feature to negotiate gzip or zstd for outbound
result bodies from `Accept-Encoding`. Compression is transport-transparent and streaming; SSE
subscription responses and bodies that already have a `Content-Encoding` are left uncompressed:

```sh
cargo run -p sparq-server --features response-compression
curl --compressed -G http://127.0.0.1:3030/sparql \
  --data-urlencode 'query=SELECT * WHERE { ?s ?p ?o }'
```

Query VERSION metadata survives protocol dataset overrides and prepared
execution. The query engine resolves its [scoped EBV rules](../sparql-query/ebv-dialects.md);
this is not a full SPARQL 1.2 protocol or language conformance claim.

## Quickstart

Run the binary (server stack is the default-on `server` feature):

```sh
# serve a Turtle file on the default address 127.0.0.1:3030 (loopback — safe default)
cargo run -p sparq-server -- --format turtle data.ttl
# no data file => empty default graph (still answers queries, just no rows)
cargo run -p sparq-server
# custom bind addr / format (turtle | ntriples | nquads | trig). A NON-loopback bind
# (e.g. 0.0.0.0) is REFUSED unless --allow-remote / SPARQ_ALLOW_REMOTE=1 (no auth — see below).
cargo run -p sparq-server -- --addr 0.0.0.0:8080 --allow-remote --format ntriples data.nt
```

Opt-in HTTP/2 switches the TCP listener from its default HTTP/1.1-only builder to the
hyper-util h1+h2 auto builder. With no certificate flags it accepts HTTP/1.1 and cleartext h2c;
supplying both PEM paths enables TLS 1.3 with ALPN `h2,http/1.1`:

```sh
cargo run -p sparq-server --features http2 -- data.ttl \
  --tls-cert ./cert.pem --tls-key ./key.pem
```

The PEM flags are a pair: supplying only one fails startup. Omitting both preserves plain HTTP.
The HTTP/1 slow-loris header deadline, body idle deadline, peer `ConnectInfo`, graceful drain, and
WebSocket upgrade remain on the same bespoke serve path; HTTP/2 uses the same router and request
middleware. sq-oprna.6

Opt-in HTTP/3 adds an encrypted QUIC/UDP listener beside the unchanged plain-HTTP TCP
listener. The two listeners dispatch through the same router; the UDP address defaults to
`--addr` and can be overridden independently:

```sh
cargo run -p sparq-server --features http3 -- data.ttl \
  --http3 --http3-addr 127.0.0.1:3443 \
  --tls-cert ./cert.pem --tls-key ./key.pem
```

Both PEM paths are required when `--http3` is set, and malformed or mismatched material
fails startup. QUIC is mandatorily encrypted. With `http3` alone the TCP listener remains plain
HTTP for proxy/backward compatibility; with `--features http2,http3` the same PEM pair also
secures TCP and negotiates h2/h1 through ALPN. The pre-1.0 h3 stack is contained behind the
default-off feature. `/subscriptions` WebSockets remain HTTP/1.1-only; clients must fall back because
HTTP/3 extended CONNECT is not implemented. Once the UDP endpoint has bound, every plain-HTTP TCP
response advertises its live port as `Alt-Svc: h3=":<port>"; ma=86400`; no header is emitted when
`--http3` is absent or startup cannot bind the QUIC listener. sq-oprna.4

> **Security: optional Bearer-token write gate; loopback by default.** With no token
> configured, every endpoint is unauthenticated (the back-compat default). Set
> `--auth-token <TOKEN>` (env `SPARQ_AUTH_TOKEN`) to require `Authorization: Bearer <TOKEN>`
> on every **write** (a SPARQL Update on `/sparql` — `application/sparql-update`, or a
> `query`/`update` body that parses as an update — and the GSP `PUT`/`POST`/`DELETE`
> methods); otherwise `401` with `WWW-Authenticate: Bearer` (constant-time compared; mirrors
> QLever's `-a <token>`). Add `--auth-token-read` (env `SPARQ_AUTH_TOKEN_READ=1`) to ALSO
> gate reads. The subscription transports — the `/subscriptions` WebSocket and the
> `/subscriptions/sse` SSE stream (both a *read* surface) — are gated by `--auth-token-read`
> too (bead `sq-cxk5`, closing the prior read-auth bypass): the SSE GET takes the
> `Authorization: Bearer` header; the WS upgrade accepts that header OR (for browsers, which
> cannot set headers on a WS handshake) a `Sec-WebSocket-Protocol: bearer.<token>` subprotocol.
> The Prometheus `GET /metrics` endpoint is gated by `--auth-token-read` as well (bead
> `sq-9jrx`): its gauges leak the live triple count and active-subscription count, so it is a
> read; `/health` stays ungated for liveness probes.
> With no read gate, both are open (back-compatible). The server binds **loopback by default** and **refuses a non-loopback
> bind** (e.g. `0.0.0.0`) unless you set `--allow-remote` (env `SPARQ_ALLOW_REMOTE=1`) OR the
> whole surface is authenticated (`--auth-token` AND `--auth-token-read`) — a write-token
> alone still leaves reads open. Deliver the token over TLS (terminate it at a proxy). For
> real per-user authz, front it with a reverse proxy / API gateway (or `sparq-solid`). SPARQL
> `SERVICE` federation is OFF
> in the default build (the `service` cargo feature is off); a `SERVICE` clause then
> errors at execution. Build with `--features service` to enable it — and even then the
> server is **default-DENY-all SERVICE**: a `SERVICE <iri>` reaches **nothing** unless its
> host is on the egress allowlist (`--service-allow` / `--service-allow-file` /
> `SPARQ_SERVICE_ALLOW`; bead `sq-4w18`). This is an SSRF guard: a `SERVICE` clause turns
> attacker-controlled query text into an outbound request from the server host (worst case
> the `169.254.169.254` cloud-metadata IP). The allowlist is enforced before any socket is
> opened, on the *resolved* IP (DNS-rebinding-safe). See "SERVICE federation (egress
> allowlist)" below.
>
> **Security response headers (always on, ASVS V14.4 / ASVS-G1; beads `sq-cmvh`, `sq-2bhm`).**
> Every response — success, streamed, error and auth-gated (`401`) alike — carries a hardening
> header set, stamped by a `map_response` layer in `harden()`:
> `X-Content-Type-Options: nosniff`,
> `Content-Security-Policy: default-src 'none'; frame-ancestors 'none'`,
> `X-Frame-Options: DENY`, and `Referrer-Policy: no-referrer`. These suit a SPARQL *data* API
> (no HTML is rendered): the tightest CSP says the body loads/runs nothing, and `frame-ancestors`
> + `X-Frame-Options: DENY` say it is never meant to be framed. Each header is only added when
> absent, so a custom handler can override one. **Deliberately omitted:** `Strict-Transport-
> Security` (the origin serves plain HTTP — HSTS belongs on the fronting TLS proxy);
> `X-XSS-Protection` (deprecated, superseded by CSP); `Cross-Origin-*` / `Permissions-Policy`
> (browser-app document policies, meaningless for a data API). **CORS is OFF by default** (no
> `Access-Control-*` header — a cross-origin browser read is blocked, the safe posture) but is an
> opt-in **first-party origin allowlist** (`sq-o7o0`; see "CORS" below). No *blanket*
> `Cache-Control: no-store` is forced: results are uncached by
> default (no `ETag`/`Cache-Control: public` is ever set), so there is nothing to tighten, and a
> blanket value would wrongly override `/health` / `/metrics` — but the sensitive auth-refusal
> (`401` from `unauthorized()`) **does** carry `Cache-Control: no-store` so a shared cache never
> retains it (`sq-2bhm`).
>
> **Error bodies carry a generic class, never internals (ASVS V7 / ASVS-G3; beads `sq-cz89`,
> `sq-j9zs`, `sq-kfel`).** Every error is the structured `{"error":"<msg>"}` envelope
> where `<msg>` is a STABLE generic category (malformed-query / auth / not-found / server-error) —
> never the caller's input, a loaded-RDF fragment, a server filesystem path, a secret, or a
> `Debug` of an internal type. The full detail goes to the server log under
> `target: "sparq_server"` (gated behind `--verbose` / `RUST_LOG`), not the response body. All
> sensitive error paths funnel through one `sanitized_error` helper; regression-guarded by
> `tests/hardening.rs` (`no_echo_*` + `FORBIDDEN_INTERNALS`) and `tests/tpf.rs`.

Point a client at it (the endpoint is `/sparql`):

```sh
# GET, query as URL param (URL-encoded); default result media is SPARQL-JSON
curl -G http://127.0.0.1:3030/sparql --data-urlencode 'query=SELECT * WHERE { ?s ?p ?o } LIMIT 5'

# POST direct: body IS the query
curl http://127.0.0.1:3030/sparql -H 'Content-Type: application/sparql-query' \
     --data 'ASK { ?s ?p ?o }'

# HTTP QUERY method (sq-b3df9, w3c/sparql-protocol#40) — query-only, interoperates with
# Oxigraph: body IS the query under Content-Type application/sparql-query; graph params
# (default-graph-uri / named-graph-uri) ride the URL query string. Same downstream query
# execution + Accept negotiation as POST; an update= form or application/sparql-update body
# is rejected (400 / 415).
curl -X QUERY http://127.0.0.1:3030/sparql -H 'Content-Type: application/sparql-query' \
     -H 'Accept: application/sparql-results+json' --data 'SELECT * WHERE { ?s ?p ?o } LIMIT 5'

# POST url-encoded form, negotiate CSV
curl http://127.0.0.1:3030/sparql -H 'Accept: text/csv' \
     --data-urlencode 'query=SELECT * WHERE { ?s ?p ?o }'

# SPARQL Update -> 204 No Content (atomic; failure -> 400, no partial effect)
curl -i http://127.0.0.1:3030/sparql -H 'Content-Type: application/sparql-update' \
     --data 'INSERT DATA { <http://ex/a> <http://ex/p> <http://ex/b> }'
```

Embed the router in your own tokio app (library use):

```rust
use sparq_core::Graph;
use sparq_server::{router, AppState};

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let graph = Graph::load_str(include_str!("data.ttl"), "turtle")?;
    let app = router(AppState::new(graph));          // axum::Router
    let listener = tokio::net::TcpListener::bind("127.0.0.1:3030").await?;
    axum::serve(listener, app).await?;
    Ok(())
}
```

## Key APIs

Library surface re-exported from `sparq_server` (behind the default `server` feature):

- `fn router(state: AppState) -> axum::Router` — builds the hardened endpoint router
  (`/sparql`, `/sparql/graph`, `/graphs/*path`, `/subscriptions`, `/subscriptions/sse`,
  `/health`, `/metrics`, plus feature-gated routes such as `/facets` and `/complete`). sq-bxog:
  `/subscriptions/sse` is the SSE transport. sq-lsp7k.5.2: `/facets` needs the
  `facets` build feature and the runtime `ServerConfig::facets` flag. sq-lsp7k.9.3:
  `/complete` similarly needs the `complete` feature and `ServerConfig::complete`.
- `AppState::new(graph: Graph) -> AppState` — default `ServerConfig`.
- `AppState::with_config(graph: Graph, config: ServerConfig) -> AppState`.
- `AppState::current(&self) -> PinnedGen` — lock-free pin of the current immutable
  generation snapshot (`PinnedGen = Arc<sparq_serve::Generation<Graph>>`; call
  `.snapshot() -> &Graph`, `.number() -> u64`, `.published_at()`, `.epochs()`).
- `AppState::apply_update(&self, sparql: &str) -> Result<u64, String>` — submit a SPARQL
  Update through the sequenced writer; **blocks** until the containing generation is
  published; returns that generation number (read-your-writes token). Call off the async
  workers (`spawn_blocking`). With **adaptive group-commit** (default; `adaptive_commit`),
  a serial interactive client commits in engine-time (µs) — the writer drains only the
  already-queued backlog and commits, instead of paying a fixed group-commit window;
  concurrent load still batches. FIFO order, per-update atomicity and durability are
  unchanged (`sq-p7kk5`).
- `AppState::at(&self, number: u64) -> Option<PinnedGen>` — pin a retained generation
  (**`time-travel` feature only**; the HTTP `?generation=N` pin does NOT need this — it
  resolves against the ring's concurrency-retention window directly, so it works in the
  default build via `sq-ci2d6`).
- `struct ServerConfig { query_timeout: Option<Duration>, update_where_timeout: Option<Duration>,
  adaptive_commit: bool,
  max_body_bytes: usize,
  max_concurrent: usize, header_read_timeout: Option<Duration>, body_read_timeout: Option<Duration>, max_results: Option<usize>, max_query_rows: Option<usize>,
  max_query_bytes: Option<usize>,
  max_decompress_ratio: usize, max_subscriptions: usize, max_subscriptions_per_conn: usize,
  verbose: bool, redact_logs: bool, allow_remote: bool, auth_token: Option<String>, auth_token_read: bool,
  service_allow: ServiceAllowlist, /* + time_travel_* / facets / complete under their features, + audit_log under audit-log feature */ }` with
  `ServerConfig::default()` and `ServerConfig::from_env()`.
  (`update_where_timeout` = separate, typically-SHORTER writer-side WHERE deadline for SPARQL
  UPDATE that bounds writer-queue **head-of-line blocking** from a slow update — `None` =
  use `query_timeout`, `sq-nulp`;
  `adaptive_commit` = **adaptive group-commit** (default `true`): a serial interactive client
  commits in engine-time (µs) rather than paying a fixed group-commit window; concurrent load
  still batches. Pure latency change — FIFO/atomicity/durability unchanged. `false` = always
  windowed. `--no-adaptive-commit` / `SPARQ_ADAPTIVE_COMMIT=0` — `sq-p7kk5`;
  `max_query_rows` = coarse memory cap; `max_query_bytes` =
  byte-accounted memory cap that also prices row WIDTH + computed-literal size — `sq-s5is`;
  `max_decompress_ratio` = zip-bomb guard — `sq-ebii`;
  `header_read_timeout` = **slow-loris guard**: max time a connection may take to send its
  complete request-header block, enforced at hyper's HTTP/1 connection layer by
  `sparq_server::serve` — `None` disables; default 15s — `sq-2gqr`;
  `body_read_timeout` = **slow-body guard** (the complement to `header_read_timeout`): an idle
  deadline between consecutive request-**body** reads, applied by `sparq_server::serve` via a
  `tower_http` `RequestBodyTimeoutLayer`/`TimeoutBody` (the timer resets after each chunk, so an
  honest large upload is not penalised — only a stall is) — closes the slow-**body** dribble a
  complete-header client could otherwise use; `None` disables; default 30s — `sq-lodb`.)
  `auth_token` (set: gates the write surface with a Bearer token, constant-time compared;
  `None`: no write auth) and `auth_token_read` (gate reads too) are honoured by the library
  `router` itself — embedders get the gate for free (`sq-zcby`).
- `fn bind_posture(addr: &SocketAddr, allow_remote: bool, auth: AuthPosture) -> BindPosture`
  — the bind gate the binary applies: `Loopback` (proceed), `RemoteAllowed { warning }`
  (proceed + log), or `RemoteRefused { message }` (refuse). `AuthPosture::{None, WriteOnly,
  ReadAndWrite}` (via `AuthPosture::from_config(&config)`) folds the token + read-gate into
  the decision: a non-loopback bind is allowed when `--allow-remote` is set OR the surface is
  fully authenticated (`ReadAndWrite`); a write-token alone (`WriteOnly`) still requires
  `--allow-remote` because reads stay open. This is a *bind-time* posture gate; per-request
  auth is the `auth_token` fields above (enforced by `router`/`harden`-wrapped handlers).
- `fn harden(routes: axum::Router, config: &ServerConfig) -> axum::Router` — wrap any
  router in the production middleware (panic→500, concurrency-limit→429, body-limit→413,
  JSON error bodies, optional trace).
- `async fn serve(listener: tokio::net::TcpListener, app: axum::Router, header_read_timeout:
  Option<Duration>, body_read_timeout: Option<Duration>, shutdown: impl Future<Output=()>) ->
  std::io::Result<()>` — the accept + graceful-drain loop the binary runs **instead of
  `axum::serve`** (`sq-2gqr` / `sq-lodb`). It is a faithful port of axum's own loop (per-connection
  task, watch-channel drain, `with_upgrades()` so the `/subscriptions` WebSocket still works) with
  two additions: (1) it installs a `hyper_util` TokioTimer and hyper's HTTP/1
  `header_read_timeout` (the slow-loris HEADER guard); (2) it optionally wraps the request body in a
  `tower_http` `RequestBodyTimeoutLayer` keyed on `body_read_timeout` (the slow-BODY guard — applied
  via `tower::util::option_layer`, so `None` is a true no-op `Identity` layer). **Why:** `axum::serve`
  never installs a timer, so hyper's header-read deadline is inert there and a slow-loris client
  holds a connection (and a `concurrency_limit` slot) open indefinitely; and even with that fixed, a
  complete-header client can still dribble the BODY to hold the slot — `body_read_timeout` closes
  that complementary hole. Pass `None` on either to opt back out of that guard. With the
  default-off `http2` feature this same function uses hyper-util's h1+h2 auto builder (h2c on a
  plain listener) and retains the timer on the builder's HTTP/1 configuration.
- `async fn serve_tls(listener: tokio::net::TcpListener, app: axum::Router, tls_config:
  Arc<rustls::ServerConfig>, header_read_timeout: Option<Duration>, body_read_timeout:
  Option<Duration>, shutdown: impl Future<Output=()>) -> std::io::Result<()>` (**`http2` feature
  only**) — TLS counterpart to `serve`; the binary supplies a TLS-1.3 config advertising
  `h2,http/1.1` via ALPN. It shares the auto-builder connection body, middleware, timeout hooks,
  peer `ConnectInfo`, and graceful drain with the cleartext feature-on path. sq-oprna.6
- Re-exports for cache layers/tests: `PinnedGen`, `GLOBAL_POD: &str`
  (`"urn:sparq:pod:global"`), and `sparq_serve::{Epoch, PodEpochs, PodId}`.
- **Response-bytes result cache** (opt-in, `sparq-serve`'s `result-cache` feature,
  OFF by default — sq-jluc). A serving-layer cache from a request
  *identity* to the pre-serialized response body, distinct from `sparq-engine`'s
  in-engine algebra-keyed `result-cache`. Public surface (feature-gated):
  `sparq_serve::{ResultCache, CacheConfig, ScopeKey, ReadFootprint, LeaseOutcome,
  CacheStats}`. **Key = canonical-query × visibility-scope × per-pod epoch-vector**
  (`ResultCache::lease`/`get`): the **scope** is the identity of the accessible
  graph set (`ScopeKey::of_graphs(AuthIndex::accessible(session, mode))`), **never**
  the WebID — bytes cached for one access scope can never be served to another (an
  access-control correctness invariant, *not* a privacy guarantee). Invalidation is
  per-pod epoch bumps (`ReadFootprint::Pods`) or the global generation
  (`ReadFootprint::Unbounded`); single-flight leases dedup a stampede; a byte-budget
  LRU + admission bound keeps it from caching oversize/streaming bodies. Wiring it
  into the axum endpoint and the canonical perf-validation are follow-ups (the perf
  targets need a canonical host).
- Serializer/negotiation helpers (always compiled, no `server` feature): module
  `sparq_server::negotiate` — `fn negotiate(accept: Option<&str>) -> Format` (lenient, always
  yields a format), `fn negotiate_or_406(accept: Option<&str>) -> Result<Format, NotAcceptable>`
  (Oxigraph-parity strict — the query path uses this; a present-but-unsatisfiable `Accept` is
  `Err(NotAcceptable)` → 406), `fn negotiate_graph(accept: Option<&str>) -> GraphFormat` and its
  strict sibling `fn negotiate_graph_or_406(...) -> Result<GraphFormat, NotAcceptable>`; module
  `sparq_server::exec` — `fn prepare(&str) -> Result<Prepared, PrepareError>` and
  `fn prepare_with_dataset(&str, &DatasetOverride) -> Result<Prepared, PrepareError>` (applies the
  SPARQL-Protocol `default-graph-uri`/`named-graph-uri` override, sq-z33x),
  `fn apply_update_dataset(&str, &UsingOverride) -> Result<String, UpdateDatasetError>` (the
  update-side `using-*` override), `enum QueryForm { Select, Ask, Construct, Describe }`; module
  `sparq_server::results`.

### In-process embedding seam — `sparq_serve::embed` (sq-xa15c, #1248)

When the consumer is **another Rust process** (e.g. `solid-server-rs`) and wants to
drop the HTTP hop entirely, embed the engine in-process via the `sparq_serve::embed`
facade instead of running `sparq-server` and talking to it over HTTP. It is the
documented **embedding seam**: thin wrappers over the engine entry points plus a
re-export of the runtime-agnostic concurrency wrapper. No axum/tokio, no HTTP.

- Data path (over one `&Graph` / `&mut Graph`): `embed::query_json(&Graph, sparql)
  -> Result<String, _>` (SPARQL-JSON), `embed::query(&Graph, sparql) ->
  Result<QueryResult, _>`, `embed::ask(&Graph, sparql) -> Result<bool, _>`,
  `embed::update_in_place(&mut Graph, sparql)` (+ `..._atomic` for all-or-nothing on
  one graph), `embed::apply_delta_nquads(&mut Graph, inserts, deletes)` (quad-level,
  per-graph; blank nodes by label), and the probes `embed::exists(&Graph) -> bool`,
  `embed::named_graph_exists(&Graph, &Term) -> bool`, `embed::metadata(&Graph) ->
  Metadata { triples, named_graphs }`. `query_json_with_budget` takes a `QueryBudget`.
- Concurrency wrapper (re-exported from the crate root): `GenerationRing` /
  `Generation` / `GraphApplier` / `Writer` (+ `RingConfig`, `WriterConfig`, `PodId`,
  `TimeTravelConfig`) — the SAME `fork → update → publish` + generation-pinning model
  `sparq-server` wraps behind its endpoint. A reader `ring.current()` pins an
  immutable snapshot; the writer publishes new generations without blocking readers.
- **Stability — API tier-1 (proposed-stable):** the proposed semver-stable embedding
  surface in the [API stability & deprecation policy](../../docs/api-stability.md), but
  **NOT yet frozen** — the formal freeze is the maintainer's to ratify on #1248 / #1346
  (pre-`1.0` minor releases MAY still change it). Pin to `sparq_serve::embed` rather
  than reaching into `sparq-core` / `sparq-engine` directly so the freeze, when
  ratified, has one well-defined shape.

## Common recipes

**1. Query forms and result negotiation.** Default result media is SPARQL-JSON. Set
`Accept` to choose (q-value aware, defaults to JSON for SELECT/ASK, N-Triples for
CONSTRUCT/DESCRIBE). <!-- sq-406acc --> An **absent / empty / `*/*` `Accept` gets
that default**; a present `Accept` that names **only unsupported media types and no wildcard is
`406 Not Acceptable`** (Oxigraph parity, w3c/sparql-protocol#40) — sparq no longer silently
falls back to JSON in that case (the EXPLAIN `Accept: text/x-sparq-explain` short-circuits this
and the Graph-Store-Protocol read path keeps its lenient default):

| Query form | Accept | Content-Type returned |
| --- | --- | --- |
| SELECT | `application/sparql-results+json` (default) / `+xml` / `text/csv` / `text/tab-separated-values` | matching results media |
| ASK | json (default) / xml | `application/sparql-results+json` / `+xml` |
| CONSTRUCT / DESCRIBE | `application/n-triples` (default) / `text/turtle` / `application/rdf+xml` / `application/ld+json` (the `jsonld` feature — **default-on**) | matching RDF media; N-Triples, prefix-compacting Turtle, RDF/XML, <!-- sq-rt6v --> or flattened JSON-LD <!-- sq-oy1f.1/.4 --> |

**CSV / TSV / XML SELECT bodies stream too** (#5517), with the CONSTRUCT / DESCRIBE contract
below: the engine materialises the `QueryResult`, then the document is written straight into
the chunked body with no row or term buffer, so the serialised bytes (which no row or byte cap
prices) are never held whole, not even for one row with a very large literal. One-chunk results keep their `Content-Length`; `HEAD` stays buffered. The library writers
`sparq_server::results::write_select_{csv,tsv,xml}` write to any `io::Write` and are
byte-identical to `select_to_{csv,tsv,xml}`.

<!-- sq-u79ee (survey §C1 / FINDINGS F21) -->
Per the W3C SPARQL Results TSV format, the **TSV** serialiser abbreviates an
`xsd:integer` / `xsd:decimal` / `xsd:double` / `xsd:boolean` literal whose lexical form is
a valid Turtle token to its **bare** token (no quotes, no `^^datatype`) — e.g. `30`, `2.2`,
`1.0E6`, `true`; everything else (incl. integer/decimal *subtypes* like `xsd:negativeInteger`
and custom datatypes) stays quoted + typed, and `xsd:string` keeps the implicit-datatype short
form. The bare token is the literal's **own** lexical form, so a data-sourced literal
round-trips its original spelling (`"1.0E6"^^xsd:double` → `1.0E6`, not canonicalised);
**computed** numerics arrive already in the engine's canonical form, so they serialise
canonically. **CSV** writes each value's bare lexical string (datatype/lang dropped — lossy by
spec); **JSON/XML** carry the full term (value + datatype) unchanged.

<!-- sq-7d3dj.34.2 -->
**SELECT-JSON streams (TTFB).** The `application/sparql-results+json` SELECT path streams its
body: the engine serialises on a blocking worker feeding a bounded channel, so the results
header + early solutions are written to the socket **before the whole result is serialised**
(first byte before full materialisation, rather than after it). The streamed body is
**byte-identical** to the single materialised JSON string (same solution order, same escaping) —
`query_json_stream_with_budget` shares one emit core with the buffered serialiser. Two response
shapes: a **single-chunk** (small, ≤ one 64 KiB chunk) result is returned buffered with a
`Content-Length`; a **multi-chunk** result streams under **chunked transfer-encoding** with **no
`Content-Length`** (the total is unknown until the last row). *Note the streaming scope:* a
DISTINCT / join / ORDER-BY SELECT must fully evaluate before any solution exists, so its first
byte still lands after the join materialises (the header is flushed the instant that finishes,
before serialisation) — the earliest-first-byte win is largest on scan-shaped and
below-parallel-threshold results. **Error mid-stream (honest
contract):** the status is chosen from the *first* chunk, so a failure detected before any byte
(parse error, or a row/byte cap / deadline the engine confirms before the header) still returns
the correct `400` / `413` / `503`. But once the header has been flushed for a genuinely
multi-chunk result, the HTTP status is committed: a later cap/deadline trip can only **truncate**
the body — a streamed `200` cannot retroactively become a `413`/`503`.

<!-- sq-7d3dj.26 -->
**Truncation safety (the invariant).** *A client MUST NOT be able to mistake a truncated stream
for a complete result.* Two mechanisms enforce it, the second strictly on top of the first:

1. **The document is never closed on a truncation.** A complete `sparql-results+json` body ends
   with `]}}`. The server WITHHOLDS the document-closing chunk until the engine confirms it
   produced the whole result, and DROPS it on any mid-stream abort — so a truncated body is not
   valid JSON and any conformant parser errors instead of silently accepting a short result.
   This is the floor guarantee and it needs no client opt-in.
2. **The reason is reported out of band.** A client that sends `TE: trailers` gets a `Trailer`
   response header plus, after the last data chunk, either `X-Sparq-Complete: true` or
   `X-Sparq-Truncated: <reason>` where the reason is `deadline` | `max-rows` | `max-bytes` |
   `cancelled` | `panic` | `error` — the same classification the pre-first-byte path maps to
   `503`/`413`. A client that did NOT negotiate trailers instead sees the chunked stream abort
   **without its terminating zero-length chunk** (a transport error), since hyper would drop a
   trailers frame for it anyway.

A worker that dies mid-result (an engine panic) is treated as a truncation, not a completion:
the completeness claim is only ever made when the engine itself returned success. **A
well-formed, correctly-terminated SHORT `200` is a forbidden outcome** — `--max-results` remains
an honest refusal, never a silent truncation, and hitting it mid-stream drops the closing `]}}`
rather than emitting a clean short document.

<!-- sq-0kq6k -->
**CONSTRUCT / DESCRIBE bodies stream (TTFB).** The RDF-graph response body is written through a
chunk sink instead of being rendered into one whole document `String` first, so the first
subject blocks reach the socket before the last triple is rendered. The two response shapes
match the SELECT-JSON path: a result that fits **one 64 KiB chunk** is returned buffered with a
`Content-Length` (unchanged wire shape for every small CONSTRUCT); a larger one streams under
**chunked transfer-encoding** with **no `Content-Length`**. Turtle, N-Triples and RDF/XML stream
genuinely; **JSON-LD does not** (a JSON-LD document is node-merged, so its writer still builds
the whole document before writing). `HEAD` deliberately stays on the buffered path so it can
keep advertising the `Content-Length` a `GET` would have carried.

Unlike the SELECT stream, the status is **never** committed early: the engine materialises the
whole result graph before serialisation starts, so a budget / deadline / evaluation failure is
always known before the first byte and is always a clean `413` / `503` / `500`. Two things can
still stop a graph body that has started streaming, and both **abort the chunked body** (no
terminating chunk) rather than end it as if complete: the RDF/XML writer refusing a predicate it
cannot encode (e.g. `rdf:about`), and a client that stops reading past the read deadline.

**Stalled readers are bounded.** A streamed body (any SELECT format, or CONSTRUCT / DESCRIBE) hands
chunks to a small bounded channel. A client that stops reading without disconnecting makes the
worker wait, but only until `query_timeout` + the 2 s grace (or a `DELETE /queries/{id}` cancel);
then the worker gives up and frees its blocking thread and the result it holds. Each streaming
worker also holds one of `max_concurrent` streaming slots until it exits, so a pile-up of slow
readers is shed with `429` instead of exhausting the blocking pool.

The buffered library writers `sparq_server::graph::triples_to_{ntriples,turtle,rdfxml}` return
`Result<String, String>`: a writer refusal is an `Err`, never a truncated document.

Honest scope: this is a **TTFB and allocation** change, not a measured peak-RSS win. Peak
process RSS on a large CONSTRUCT is dominated by materialising the result `Vec<Triple>` (and the
solutions it is instantiated from), which both paths do — see
[`bench/construct-stream/README.md`](../../bench/construct-stream/README.md) for the harness and
the first-read finding.

<!-- sq-7d3dj.34.1 -->
**Single parse per request (HTTP floor).** The read path parses each request query with
`spargebra` exactly ONCE — the server parses to classify the form + apply any protocol dataset
override, then hands the resulting algebra straight to the engine's `*_prepared` entry points
(`query_json_stream_prepared_with_budget` for JSON SELECT, `ask_prepared_with_budget` for ASK),
so the engine does not re-parse the query string. This shaves one full parse off the per-request
floor for ARBITRARY novel queries (no query cache — parsing is still paid, just not twice);
negligible on a trivial `ASK{}` (sub-µs), and larger on realistic multi-pattern queries.

```sh
curl -G http://127.0.0.1:3030/sparql -H 'Accept: application/sparql-results+xml' \
     --data-urlencode 'query=SELECT ?s WHERE { ?s ?p ?o }'
# prefix-compacting Turtle:
curl -G http://127.0.0.1:3030/sparql -H 'Accept: text/turtle' \
     --data-urlencode 'query=CONSTRUCT { ?s ?p ?o } WHERE { ?s ?p ?o }'
# RDF/XML:
curl -G http://127.0.0.1:3030/sparql -H 'Accept: application/rdf+xml' \
     --data-urlencode 'query=CONSTRUCT { ?s ?p ?o } WHERE { ?s ?p ?o }'
# JSON-LD (flattened) — default-on, works on the standard build: sq-oy1f.1/.4
curl -G http://127.0.0.1:3030/sparql -H 'Accept: application/ld+json' \
     --data-urlencode 'query=CONSTRUCT { ?s ?p ?o } WHERE { ?s ?p ?o }'
```

> **HTTP `QUERY` method (sq-b3df9, w3c/sparql-protocol#40, epic sq-my8wd) — query-only,
> Oxigraph-interop.** `/sparql` accepts the registered HTTP `QUERY` verb in addition to
> GET/POST. It is a new INPUT path that feeds the SAME query execution + Accept negotiation as
> POST, so all the result-media rows above apply unchanged. Mirroring Oxigraph
> (`("/sparql", "POST" | "QUERY")`, `let is_query = method == "QUERY"`):
> - **Send the query** as the raw `application/sparql-query` body (preferred), OR as the
>   `query=` value of an `application/x-www-form-urlencoded` body. No other Content-Type is
>   accepted (else **415**); missing Content-Type is **415**.
> - **Dataset graphs** (`default-graph-uri` / `named-graph-uri` / `union-default-graph`) ride
>   the **URL query string**, never the body — even when the query is the raw body.
> - **Query-only:** an `update=` form field is a **400** and an `application/sparql-update`
>   body is a **415** (it is not a valid operation under QUERY). Use POST for an update.
> - It enforces the SAME auth / egress gates as GET/POST (a QUERY is a read — gated by
>   `--auth-token-read`). It does **not** emit `Cache-Control` / `Content-Location` headers
>   (Oxigraph does not either).
> ```sh
> curl -X QUERY 'http://127.0.0.1:3030/sparql?default-graph-uri=http://ex/g1' \
>      -H 'Content-Type: application/sparql-query' \
>      -H 'Accept: text/csv' \
>      --data 'SELECT * WHERE { ?s ?p ?o }'
> ```

<!-- sq-jaj38: comment separates the two adjacent blockquotes (markdownlint MD028). -->

> **SPARQL 1.1 Protocol conformance lane (sq-jaj38, epic sq-my8wd) — what is ratcheted.** The
> protocol surface above is now covered by a dedicated W3C **SPARQL 1.1 Protocol (HTTP)**
> conformance suite in `sparq-conformance` (opt-in `http-protocol` feature, OFF by default; it
> reuses the in-process loopback server — `sparq_server::serve` on an ephemeral `127.0.0.1:0`
> port — and drives RAW HTTP at the bound port, NOT the federated SERVICE transport, so it does
> not touch the engine's egress allowlist). It ratchets a MEASURED PASS floor over: query via
> GET / POST-urlencoded / POST-direct, the `QUERY` method, update via POST, the
> `default-graph-uri` / `named-graph-uri` overrides, SELECT/ASK negotiation (SRJ / SRX / CSV /
> TSV), a **present-but-unsatisfiable `Accept` → 406 Not Acceptable** (Oxigraph parity,
> w3c/sparql-protocol#40 — <!-- sq-406acc --> formerly a divergence, now a genuine
> PASS that raised the floor 20→21), and the **200 / 400 / 405 (with `Allow`) / 406 / 415**
> status codes. **Honest boundary:** two behaviours remain DOCUMENTED DIVERGENCES (reported
> separately, NOT summed into the floor, so they never inflate the conformance number): an
> **absent / `*/*` `Accept` defaults to SPARQL-results JSON** (a W3C-permitted default
> representation — only a *present-but-unsatisfiable* `Accept` is a 406), and an **ASK with
> `Accept: text/csv` falls back to a JSON boolean** (CSV/TSV have no boolean serialisation). Run
> it with
> `cargo test -p sparq-conformance --features http-protocol --test http_protocol_suite`; the row
> is in the central scoreboard (`W3C SPARQL 1.1 Protocol (HTTP)`).

<!-- sq-1uuxz: comment separates the two adjacent blockquotes (markdownlint MD028). -->

> **Service Description + Graph Store Protocol conformance lane (sq-1uuxz, epic sq-my8wd) — what
> is ratcheted.** The federation-descriptor + GSP write surfaces (see "Federation discovery" and
> the Graph-Store-Protocol section below) are covered by a dedicated **SD + GSP** conformance suite
> in `sparq-conformance` (opt-in `federation-descriptors` feature, OFF by default; it reuses the
> in-process loopback server — `sparq_server::serve` on an ephemeral `127.0.0.1:0` port, stood up
> with the server's `federation-descriptors` runtime flag ON — and drives RAW HTTP at the bound
> port, so it does not touch the engine's egress allowlist). It ratchets a MEASURED PASS floor
> over **(A) the Service Description** (`GET /sparql` with no query): the `sd:Service` advertises
> exactly the result/input formats (SRJ/SRX/CSV/TSV + Turtle/N-Triples/RDF-XML), the query/update
> languages, the SPARQL versions (`sd:supportedVersion` 1.0/1.1) and `sd:BasicFederatedQuery`
> that the server GENUINELY implements — **no over-advertising** (each advertised result format is
> cross-checked against a real SELECT request, and JSON-LD — not served in this build — must NOT
> appear) — and **(B) the Graph Store Protocol**: a GET/PUT/POST/DELETE round-trip on a named graph
> (indirect `?graph=<iri>` + direct `/graphs/<path>`) and the default graph (`?default`), VERIFYING
> store state after every op (PUT→GET-back-equal; PUT replaces; POST merges; DELETE removes;
> **200/201/204/400/404/405 (with `Allow`)/415**). **Honest boundary:** a GSP read of an ABSENT
> named graph is **200 + empty graph, NOT 404** (GSP-permitted — sparq treats an empty graph as
> existing); this is a DOCUMENTED DIVERGENCE, reported separately and NOT summed into the floor. Run
> it with `cargo test -p sparq-conformance --features federation-descriptors --test sd_gsp_suite`;
> the row is in the central scoreboard (`SPARQL 1.1 Service Description + Graph Store Protocol`).

<!-- sq-b3df9: comment separates the two adjacent blockquotes (markdownlint MD028). -->

> **JSON-LD content negotiation (`jsonld` feature — default-on, sq-oy1f.4).** The
> server speaks `application/ld+json` out of the box (the `jsonld` feature is in the default set —
> a maintainer-directed exception to opt-in-by-default). `application/ld+json` joins the
> q-value-aware RDF negotiation in BOTH directions: a CONSTRUCT/DESCRIBE or a Graph-Store-Protocol
> read with `Accept: application/ld+json` is served as the engine's *flattened* JSON-LD (a
> `{"@graph": […]}` node-object document that `toRdf`-round-trips to the same graph), and a GSP
> `PUT`/`POST` with `Content-Type: application/ld+json` is parsed into the store via the engine's
> JSON-LD parser. Toggleable off via `--no-default-features --features server`: then
> `application/ld+json` is unrecognised — an `Accept` for it falls back to a supported graph format
> (never a 406 — the endpoint always has a representation), and a write body in it is a plain `415`
> — byte-identical to a JSON-LD-disabled build. What is default-on now: JSON-LD parse + serialise
> (flattened) + content-negotiation; full conneg-conformance ratcheting is on the sq-oy1f roadmap.

<!-- sq-7d3dj.30.13: comment separates the two adjacent blockquotes (markdownlint MD028). -->

> **Default-on algebra rewrite (`algebra-rewrite` feature — sq-7d3dj.30.13).** The
> server's default set also lights sparq-engine's pre-execution algebra rewrite pass (#1735): a
> result-equivalent `FILTER(?v = <iri>)` IRI-constant folding + `FILTER(!bound)` anti-join applied
> at parse time, so the shipped server executes the same plans the CLI and the canonical benchmarks
> measure. IRI constants only (a literal equality is never rewritten — the `sq-lr2ii` avoidance
> contract); zero new dependencies. Drop it with `--no-default-features --features server,jsonld`
> for an explicitly rewrite-dark build; the sparq-engine LIBRARY default remains OFF for lean
> library consumers.

<!-- sq-7d3dj.30.15: comment separates the two adjacent blockquotes (markdownlint MD028). -->

> **Default-on DPccp join-order planner (`dp-planner` feature — sq-7d3dj.30.15).** The
> server's default set also lights sparq-engine's DPccp planner (sq-7d3dj.30.5): a connected BGP
> with 3 or more patterns that fits the connected-subgraph budget is planned as a cost-optimal
> BUSHY join tree instead of by greedy GOO. It is DEFAULT-ON once compiled, so every request gets
> it with no explicit install, and it is result-equivalent — only join ORDER changes, never the
> answer. This closes the gap where sq-7d3dj.30.5 lit the planner in `sparq-cli` alone, which made
> an HTTP-measured query plan differently from the CLI-measured one the canonical benchmarks use.
> Zero new dependencies. Drop it with `--no-default-features --features server,jsonld` for an
> explicitly greedy-GOO build; the sparq-engine LIBRARY default remains OFF for lean library
> consumers.

**2. EXPLAIN a query plan (no execution) or analyze (execute + per-operator trace).**
`text/plain` response. Use `explain` / `explain=plan` (or `Accept: text/x-sparq-explain`)
for the dry run, `explain=analyze` to run + trace (SELECT/ASK only):

```sh
curl -G 'http://127.0.0.1:3030/sparql?explain=true' \
     --data-urlencode 'query=SELECT * WHERE { ?a <http://ex/knows> ?b . ?b <http://ex/age> ?age }'
```

**Structured plan tree (`explain-json` feature, default-on for the server binary —
sq-ixc3.19).** `Accept: application/x-sparq-explain+json` answers the SAME `explain` /
`explain=analyze` surface with the typed plan tree (`explain_json::PlanNode`) as camelCase
JSON — per operator `{"operator", "estimated", "actual", "nanos", "qError", "children"}`
(the sq-jbqh4 schema contract the GUI plan explorer renders; `qError` =
max(est/actual, actual/est)). Like the text CT, the JSON `Accept` alone requests a
plan-only explain. A `--no-default-features --features server,…` build answers it **406**
(the text explain still works) so clients degrade explicitly, never mis-parse text as JSON:

```sh
curl -G -H 'Accept: application/x-sparq-explain+json' \
     'http://127.0.0.1:3030/sparql?explain=analyze' \
     --data-urlencode 'query=SELECT * WHERE { ?a <http://ex/knows> ?b . ?b <http://ex/age> ?age }'
```

**3. Generation-pinned snapshot reads (DEFAULT build — `sq-ci2d6`).** Every `/sparql` response
carries the `Sparq-Generation` header (the generation the response was produced against; an
update's `204` carries the generation *containing* the write — the read-your-writes token).
Capture it and pin a later read with `?generation=N` (URL param or url-encoded body — body wins)
to get an **immutable snapshot** of the store as of that generation. This is available with **no
feature enabled**: the pin is bounded to the generation ring's **concurrency-retention window** —
the last **K = 4** generations older than current are always kept (`sparq_serve::ring::DEFAULT_RETAIN`;
`RingConfig::retain`). That is exactly the window that makes **multi-request `LIMIT`/`OFFSET`
pagination snapshot-consistent**: pin one generation, page it, and the pages union to the
single-shot result at that generation even if writes interleave (with a deterministic order —
add `ORDER BY`, or rely on the stable order over the immutable snapshot):

```sh
# read-your-writes: capture the generation an update lands in (default build — no feature)
G=$(curl -si http://127.0.0.1:3030/sparql -H 'content-type: application/sparql-update' \
      --data 'INSERT DATA { <http://ex/a> <http://ex/p> <http://ex/b> }' \
      | grep -i sparq-generation | tr -d '\r' | awk '{print $2}')
# page a large read pinned to that generation — page 1, then page 2, still consistent
# even if another client writes between the two requests:
curl -G http://127.0.0.1:3030/sparql --data-urlencode "generation=$G" \
     --data-urlencode 'query=SELECT ?child WHERE { <c> <member> ?child } ORDER BY ?child LIMIT 1000 OFFSET 0'
curl -G http://127.0.0.1:3030/sparql --data-urlencode "generation=$G" \
     --data-urlencode 'query=SELECT ?child WHERE { <c> <member> ?child } ORDER BY ?child LIMIT 1000 OFFSET 1000'
```
**Honest boundary (the retention contract).** The default window is bounded by the ring's
*concurrency* retention (K = 4), **not** a durable history: a pin more than K generations behind
current has **aged out** → `410 Gone` (the snapshot is gone; re-read the current generation and
restart pagination — the server **never** silently substitutes a different generation). If a
pagination sweep must survive more than K interleaved writes, build with the opt-in **`time-travel`**
feature, which EXTENDS retention (`--time-travel-generations N`, `--time-travel-max-age SECS`) so
`?generation=N` reaches far older snapshots — same header/pin mechanics, wider window:

```sh
cargo run -p sparq-server --features time-travel -- data.ttl --time-travel-generations 32
```
Status: aged-out generation → `410 Gone`; never-published / unparsable / pinning an
*update* (an update always applies to current) → `400`. All identical in both feature states —
`time-travel` only changes how far back a pin can reach.

**4. WebSocket subscriptions (SEPA-style live SELECT).** Connect to
`ws://127.0.0.1:3030/subscriptions`, send `subscribe`, get `subscribed` + an initial
`notification` (sequence 0 = full result as `addedResults`), then added/removed bindings
diffs after each committed update that changes the result:

```text
client:  {"subscribe": {"query": "SELECT ?s WHERE { ?s <http://ex/age> ?o }", "alias": "ages"}}
server:  {"subscribed": {"id": 1, "alias": "ages"}}
server:  {"notification": {"id": 1, "sequence": 0, "addedResults": {…full result…},
                           "removedResults": {"head":{"vars":["s"]},"results":{"bindings":[]}}}}
         …POST /sparql update commits…
server:  {"notification": {"id": 1, "sequence": 1, "addedResults": {…}, "removedResults": {…}}}
client:  {"unsubscribe": {"id": 1}}
server:  {"unsubscribed": {"id": 1}}
```
`addedResults`/`removedResults` are each full SPARQL-JSON results objects. Refusals and
failed re-evaluations come back as `{"error": {"message": …, "id"?: n}}`.

sq-cxk5: when `--auth-token-read` is set, the upgrade is gated behind the read
token (`401` before upgrade otherwise). A non-browser client sends `Authorization: Bearer
<TOKEN>` on the handshake; a **browser** (which cannot set WS handshake headers) passes it as
a subprotocol: `new WebSocket("ws://host/subscriptions", ["bearer." + token])`. The server
takes the substring after the `bearer.` prefix as the token, validates it (constant-time),
and echoes the subprotocol back per RFC 6455. With no read token configured, the upgrade is
open (back-compatible).

**4b. SSE subscriptions (`text/event-stream`).** sq-bxog: the SAME subscription
engine over Server-Sent Events, for clients that prefer a plain HTTP GET stream to a
WebSocket. `GET /subscriptions/sse?query=<SELECT>[&alias=<x>]` opens one subscription per
stream (the query is in the query string — SSE is one-way, so there is no `subscribe`/
`unsubscribe` frame; close the stream to unsubscribe). The events carry the SAME JSON as
the WS path — only the framing differs (`event:` / `data:` / `id:` lines, blank-line
terminated, `: ping` keep-alive comments hold idle connections open). The SSE `id:` mirrors
the per-subscription `sequence`.

```sh
curl -N 'http://127.0.0.1:3030/subscriptions/sse?query=SELECT%20?s%20WHERE%20{%20?s%20%3Chttp://ex/age%3E%20?o%20}&alias=ages'
```
```text
event: subscribed
data: {"subscribed":{"id":1,"alias":"ages"}}

event: notification
id: 0
data: {"notification":{"id":1,"sequence":0,"alias":"ages","addedResults":{…full result…},"removedResults":{…empty…}}}

  …POST /sparql update commits…
event: notification
id: 1
data: {"notification":{"id":1,"sequence":1,"alias":"ages","addedResults":{…},"removedResults":{…}}}
```
sq-cxk5: like the WS path, when `--auth-token-read` is set this GET is gated
behind the read token via the `Authorization: Bearer <TOKEN>` header (it is a plain GET, so
the header is the only auth channel — no WS subprotocol) — `401` before the stream opens
otherwise. A registration refusal (missing/non-SELECT/malformed `query` → `400`; capacity/budget →
`503`) is returned as a normal `{"error":"…"}` JSON HTTP response BEFORE the stream opens —
SSE cannot set a status once the stream is flowing. A later re-evaluation failure ends the
stream with a final `event: error` frame. Both transports share one registry + change
source, so the per-conn / server-wide subscription caps and the `sparq_active_subscriptions`
gauge count SSE streams and WS subscriptions together.

**5. Graph Store read + write + operational endpoints.**

```sh
# READ (GET/HEAD): serialises the addressed graph in the Accept-negotiated RDF syntax
# (default N-Triples; also text/turtle = prefix-compacting Turtle, application/rdf+xml = RDF/XML,
#  and application/ld+json = flattened JSON-LD with `--features jsonld` sq-oy1f.1)
curl http://127.0.0.1:3030/sparql/graph?default                 # GSP indirect (default graph)
curl 'http://127.0.0.1:3030/sparql/graph?graph=http://ex/g'     # GSP indirect (named graph)
curl http://127.0.0.1:3030/graphs/whatever                      # GSP direct (request URI is the graph IRI)
curl -H 'Accept: application/rdf+xml' http://127.0.0.1:3030/sparql/graph?default   # RDF/XML read sq-rt6v
curl -H 'Accept: application/ld+json' http://127.0.0.1:3030/sparql/graph?default   # JSON-LD read (--features jsonld) sq-oy1f.1

# WRITE (sq-gxsj): body is RDF, format by Content-Type
#   (turtle | n-triples | n-quads | trig | application/rdf+xml sq-rt6v
#    | application/ld+json with `--features jsonld` sq-oy1f.1)
# PUT = REPLACE graph contents (201 if created, 204 if replaced):
curl -X PUT 'http://127.0.0.1:3030/sparql/graph?graph=http://ex/g' \
     -H 'content-type: text/turtle' --data '<http://ex/s> <http://ex/p> <http://ex/o> .'
# POST = MERGE (additive); selector-less POST to /sparql/graph creates a fresh server-named graph:
curl -X POST 'http://127.0.0.1:3030/sparql/graph?graph=http://ex/g' \
     -H 'content-type: application/n-triples' --data '<http://ex/s2> <http://ex/p> <http://ex/o2> .'
# DELETE = DROP the graph (204; 404 if a named graph is absent; ?default → CLEAR DEFAULT, always 204):
curl -X DELETE 'http://127.0.0.1:3030/sparql/graph?graph=http://ex/g'

# PATCH = atomic, graph-scoped in-place MODIFY (sq-hj4n; 204 on success). Two body dialects:
#   1) application/sparql-update (ALWAYS-ON) — the body IS a SPARQL Update, applied atomically
#      through the same writer, with its WHERE dataset scoped to the addressed graph:
curl -X PATCH 'http://127.0.0.1:3030/sparql/graph?graph=http://ex/g' \
     -H 'content-type: application/sparql-update' \
     --data 'DELETE DATA { GRAPH <http://ex/g> { <http://ex/s> <http://ex/p> <http://ex/o> } } ;
             INSERT DATA { GRAPH <http://ex/g> { <http://ex/s> <http://ex/p> <http://ex/o2> } }'
#   2) text/n3 (Solid N3-Patch, OPT-IN: needs the `n3-patch` build feature AND --n3-patch / SPARQ_N3_PATCH=1;
#      else 415). A solid:InsertDeletePatch translated into ONE atomic graph-scoped DELETE/INSERT … WHERE:
curl -X PATCH 'http://127.0.0.1:3030/sparql/graph?default' \
     -H 'content-type: text/n3' --data '@prefix solid: <http://www.w3.org/ns/solid/terms#>.
@prefix ex: <http://ex/>.
_:p a solid:InsertDeletePatch;
  solid:where   { ?s ex:name "Alice" . };
  solid:deletes { ?s ex:age 30 . };
  solid:inserts { ?s ex:age 31 . }.'

curl http://127.0.0.1:3030/health                               # -> "ok"
curl http://127.0.0.1:3030/metrics                              # Prometheus text exposition (gated by --auth-token-read; sq-9jrx)

# Admin WAL compaction / vacuum for ERASURE-COMPLETENESS (sq-x32t). POST-only; gated by the
# WRITE token. Physically purges data removed by DELETE / DROP (incl. orphaned literal VALUES) from the
# on-disk store so a logical erasure is followed by real erasure. 200 ok; 409 if in-memory
# (no --persist, nothing to purge); 503 on a durable-write error (check server recovery logs):
curl -X POST -H 'Authorization: Bearer <TOKEN>' http://127.0.0.1:3030/admin/compact

# Online consistent-snapshot backup + restore (feature `backup`, default OFF). POST-only, WRITE-gated.
# Backup streams a single self-describing artifact of the LIVE store WHILE SERVING (no stop-the-world):
curl -X POST -H 'Authorization: Bearer <TOKEN>' http://127.0.0.1:3030/admin/backup -o snapshot.spqb
# Restore atomically installs a store rehydrated from that artifact (in-memory; fail-closed):
curl -X POST -H 'Authorization: Bearer <TOKEN>' --data-binary @snapshot.spqb http://127.0.0.1:3030/admin/restore
# On a --persist server, opt into write-through so the restore survives a restart (else 409):
curl -X POST -H 'Authorization: Bearer <TOKEN>' --data-binary @snapshot.spqb 'http://127.0.0.1:3030/admin/restore?persist=true'
# Restore on start (bootstrap a fresh node / PITR base):  sparq-server --restore snapshot.spqb
#   …into a durable store (survives restart):             sparq-server --persist DIR --restore snapshot.spqb --restore-persist
# Incremental change-stream / point-in-time recovery (PITR): a DELTA between a retained
# generation N and the current generation (replayed forward onto the matching base):
curl -X POST -H 'Authorization: Bearer <TOKEN>' 'http://127.0.0.1:3030/admin/backup/delta?from=0' -o d0.spqd
# Recover to the chosen point: restore the base, then replay the delta chain (oldest first):
sparq-server --restore snapshot.spqb --restore-delta d0.spqd --restore-delta d1.spqd
```

`/metrics` is hand-rolled Prometheus text exposition (no metrics dependency); the
middleware wraps the whole hardening stack, so shed (`429`), body-limit (`413`) and panic
(`500`) responses are counted with the status the client saw:

| Metric | Type | What |
| --- | --- | --- |
| `sparq_http_requests_total{endpoint,status}` | counter | requests by endpoint + response status |
| `sparq_query_duration_seconds` | histogram | wall time of `/sparql` (query + update); buckets 1 ms … 10 s |
| `sparq_active_subscriptions` | gauge | active WebSocket subscriptions (scrape time) |
| `sparq_graph_triples` | gauge | triples in the published graph (scrape time) |
| `sparq_updates_total` | counter | successfully applied SPARQL updates |

**`POST /admin/compact` — WAL compaction / vacuum (erasure-completeness, `sq-x32t`).** A logical
`DELETE` / `DROP GRAPH` retracts data from the live view but leaves the superseded bytes in earlier
`--persist` WAL segments (and the dictionary) until a compaction folds the live state into a fresh
base. This admin op does that on demand: it **physically rewrites** the on-disk store to only the
current live triples, with a **re-interned (purged) dictionary**, then **atomically swaps** the
directory (rollback-safe two-rename + WAL truncate; an interrupted swap is healed on the next
open). So a deleted triple's value — including an orphaned **literal value** (e.g. personal data) —
is gone from disk, not just hidden. It runs on the single writer thread strictly **between
batches** (no race with a concurrent write), preserves the live triple set **exactly** (no
generation published; reads keep flowing throughout). **POST-only**, gated by the **write** token
(`--auth-token`), like an UPDATE. Responses: `200` ok; `409` if the server is in-memory (no
`--persist` — there is no on-disk history to purge, so a no-op success would mislead); `503` on a
durable-write error. Reads continue from the published snapshot. Check the server logs for
recovery status; a frozen store refuses further writes until it is reopened. **Offline equivalent:** stop the
server and run `sparq-cli compact <persist-dir>` (see the `cli` skill). **Honest scope:** this
scrubs the engine's own on-disk segments + dictionary; it cannot reach bytes already copied off-box
(filesystem snapshots, COW history, external backups) — those are the operator's responsibility
(see `compliance/privacy/retention-erasure-runbook.md` §7a/§7b).

**`POST /admin/backup` + `POST /admin/restore` — online consistent snapshot backup/restore
(feature `backup`, default OFF; `sq-o5bi`).** An ONLINE point-in-time backup of the live serving
store, distinct from the offline `sparq-cli save` (stop-the-world, index rebuild) and from the
`--persist` per-graph WAL. **`/admin/backup`** pins the CURRENT generation lock-free and serialises
it off the immutable `Arc` — so it runs **while serving**: readers never block the writer and the
writer never blocks readers throughout. The response is **one self-describing artifact** (Stardog
backup-ID model, "Option A"): a small textual header recording the generation number (= the single
writer's seq), the per-pod epoch vectors, the triple count and a body integrity digest, then the
full dataset (default + named graphs) as N-Quads. **`/admin/restore`** imports such an artifact and
**atomically installs** a freshly-built ring+writer rehydrated from it — readers in flight keep
serving from the old store until they release their pin; every read/update after the swap sees the
restored store. **Fail-closed:** a corrupt / truncated / version-mismatched / non-artifact body is
rejected (`400`) and the live store is left **untouched** (the new core is built fully before the
swap). Both routes are **POST-only** and gated by the **write** token (the admin gate). Responses:
backup `200` (`application/octet-stream`); restore `200` on success, `400` on a rejected artifact.
**Single-flight (`sq-fy8ci`):** a restore posted while another is still in flight is rejected
**`409`** (`a restore is already in progress`) instead of being silently serialized behind it by
the writer thread (last-writer-wins) — retry after the first completes. Embedders driving
`AppState::restore_from` directly can claim the same permit via `AppState::try_begin_restore()`
(an RAII `RestoreGuard`; dropping it — even on a panic — releases the permit).

**Restore into a live durable store (`sq-ft7u`).** On a `--persist` server, a plain
`/admin/restore` (no opt-in) is **`409`** — an in-memory-only swap on a durable server would be
silently lost on the next restart (a footgun). Add **`?persist=true`** to write the restore
**THROUGH to the durable directory**, so it **survives a restart** (the on-disk base becomes the
restored image). The durable swap runs **on the single writer thread** (sequenced with updates — no
lock, no race with a concurrent durable commit) and is **crash-safe**: the imported image is written
to a sibling and swapped in with a **two-rename directory swap** (parent dir fsync'd between renames)
that an interrupted crash heals deterministically (`Graph::restore_into_durable` reuses the exact WAL
compaction swap + `recover_compaction` healer). **Fail-closed throughout:** the artifact is imported
+ validated **before** any on-disk change, so a corrupt artifact is `400` with the durable store
**untouched** and no swap-sibling leftovers. A swap I/O error is recovered at once under the
store's lock: rolled back, the OLD store is intact and the writer appends to it; completed, the
restore succeeded. Only if neither works is the durable graph frozen (every later update refused
until a restart re-opens the directory, which heals it to old-or-new); the writer stays alive. A
store whose parent directory is not writable (no `<dir>.lock` beside it) serves, but its restores
and compactions are refused: they rename the directory. `?persist=true` on an **in-memory** server is `409` (no durable dir). **Restore-on-start:**
`--restore <FILE>` / `SPARQ_RESTORE` seeds the in-memory store before binding (bootstrap for
horizontal-scaling stage-2 + PITR base); with `--persist DIR` it is **refused unless** you add
**`--restore-persist`** / `SPARQ_RESTORE_PERSIST=1`, which writes the a

[…] pełny plik w paczce .zip

Versions

The database has no other skills named http-server.

Database snapshot: 13.11.2026 · package version 7d385afaef5c (SHA-256 digest of the entire package)

Downloads in the last 30 days: 0 · ranking

Report a problem with this skill: harmful content, incorrect descriptions or an author’s removal request.

Similar skills

  • 91sparql-query
    Run SPARQL 1.1/1.2 queries (SELECT/ASK/CONSTRUCT/DESCRIBE) and UPDATE against the sparq RDF engine in Rust — load RDF into a sparq_core::Graph, then use sparq_engine::{query, ask, query_json, count, construct, describe, update}; covers property paths, RDF 1.2 triple terms,…
  • 87agent-tools
    Use when an LLM/agent should access a sparq RDF dataset over the Model Context Protocol (MCP) as first-class tools — run SPARQL queries, mine the dataset schema, list class profiles or namespace prefixes, read stats or a VoID descriptor, optionally SHACL-validate against…
  • 100open-ontologies
    AI-native ontology engineering using 110 MCP tools backed by an in-memory Oxigraph triple store. Build, validate, query, and govern RDF/OWL ontologies with a generate-validate-iterate loop. Use when building ontologies, knowledge graphs, RDF data, SPARQL queries, BORO/4D…
  • 90semantic-web
    Design Semantic Web structures, Ontologies, and Meta-knowledge graphs. Use when: design ontology, semantic web, knowledge graph architecture, rdf data model, sparql, linked data.
  • 100rete-from-graph
    Build a queryable `.rete` file from ANY graph-based data source — an RDF dump (.nt/.nq/.ttl/.rdf/.owl), a SPARQL endpoint, a Wikibase, an OWL ontology, GeoJSON, tabular/CSV, a GBIF Darwin-Core archive, a TEI corpus, or a JSON API. Use whenever the task is "turn this…
  • 95devkg-sparql
    Query the Dev Knowledge Graph via SPARQL instead of grepping raw session files. Use this when asked about technologies, relationships between tools, session history, where a topic was discussed, or cross-platform knowledge. Prefer provenance-first SPARQL (message + session) over…

Feedback and reports

Your message goes to Bartosz Sokoliński. An email address is needed only for a reply. See the privacy policy.