diff --git a/CHANGELOG.md b/CHANGELOG.md index 9b74b21..34ac0ca 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -9,9 +9,14 @@ versions may change the store format and the API; the release notes say how to u ### Fixed +- Query page: MatGUI's **Explain** tab of the results showed no plan and said "No engine recognised for this endpoint", as it knows only QLever, GraphDB, Stardog, Blazegraph and Neptune. For this server's own endpoints it now asks `/{ds}/explain` (the Engine list reads "Detect (TripleTrail)") and draws the plan as a tree with the rows and time of each step. See [the guide](docs/guide/02-first-steps.md#see-how-a-query-ran). - A dataset's turn (`maxConcurrent`) ends once its answer is read to its end, before the last bytes are written, as the caller's turn already did: a client that sends its next request as soon as an answer is in no longer waits for, or is refused for, the turn the answer still held, and `/$/stats` no longer shows it running. - A vector graph saved to its file (`.networks/vectors/`) counts as being made until the file is written: once its status says done, nothing writes to the folder any more. +### Changed + +- Every answer carries `Server: TripleTrail/` instead of `tiny-http (Rust)`, and `--cors` lets pages read it, so query tools can recognise the engine by it. The Explain plugin of MatGUI and YASGUI does not yet: its TripleTrail engine waits for a plugin release. + ## 0.1.0-rc.2 - 2026-11-20 The second release candidate: vector search for GraphRAG, more full-text syntaxes, a richer Map page and describe pages, and fixes to spatial filters over property paths. diff --git a/crates/tripletrail-server/src/lib.rs b/crates/tripletrail-server/src/lib.rs index f584471..8f63d22 100644 --- a/crates/tripletrail-server/src/lib.rs +++ b/crates/tripletrail-server/src/lib.rs @@ -1357,6 +1357,9 @@ fn handle(state: &Arc, mut request: Request) { #[cfg(feature = "replication")] const MAX_SYNC_WAITERS: usize = 1024; +/// The `Server` header of every answer. +const SERVER: &str = concat!("TripleTrail/", env!("CARGO_PKG_VERSION")); + /// Sends `reply` (with `headers`), then records and logs the request. fn send_reply( state: &Arc, @@ -1379,6 +1382,9 @@ fn send_reply( for (name, value) in &reply.headers { headers.push(header(name, value)); } + // Names the engine, where tiny_http would say "tiny-http (Rust)": MatGUI's Explain view + // recognises TripleTrail by it, and asks /{ds}/explain for the plan. + headers.push(header("Server", SERVER)); let origin = if state.options.cors { Some("*") } else { @@ -1398,7 +1404,7 @@ fn send_reply( // Headers a page on that origin may read (#223: the JavaScript client's `incomplete`). headers.push(header( "Access-Control-Expose-Headers", - "X-Result-Incomplete, X-Cache, X-Truncated", + "X-Result-Incomplete, X-Cache, X-Truncated, Server", )); if *request.method() == Method::Options { headers.push(header( diff --git a/crates/tripletrail-server/tests/admin.rs b/crates/tripletrail-server/tests/admin.rs index 17e0ce1..1cccb19 100644 --- a/crates/tripletrail-server/tests/admin.rs +++ b/crates/tripletrail-server/tests/admin.rs @@ -1998,6 +1998,80 @@ fn the_web_ui_and_its_embedded_matgui() { assert_eq!(status(get(&off, "/$/ui/")), 404); } +/// MatGUI's Explain view knows no TripleTrail engine of its own, so the Query page teaches it +/// one: for this server's `…/sparql` endpoints it POSTs the query to `…/explain` and draws the +/// plan from `plan.plan`, whose steps carry `name`, `number of results`, `duration in seconds` +/// and `children`. Before, the view said "No engine recognised" and showed no plan. +#[test] +fn the_query_page_explain_view_reads_the_plan_of_this_server() { + let dir = temp_dir("explain-view"); + let s = start(&dir, Vec::new()); + s.admin("POST", "/$/datasets") + .query("name", "plan") + .query("type", "mem") + .call() + .unwrap(); + assert_eq!( + s.update( + "plan", + "INSERT DATA { . + }" + ), + 200 + ); + let script = ureq::get(&format!("{}/$/ui/app.js", s.base)) + .call() + .unwrap() + .into_string() + .unwrap(); + for wired in [ + "registerPlugin(\"Explain\", TripleTrailExplain)", + "\"/explain\"", + "\"Content-Type\": \"application/sparql-query\"", + "r.plan.plan", + "n[\"number of results\"]", + "n[\"duration in seconds\"]", + "r.plan[\"planning duration in seconds\"]", + ] { + assert!(script.contains(wired), "app.js no longer has {wired}"); + } + // The request the view sends, and the fields it reads from the answer. + let r = ureq::post(&format!("{}/plan/explain", s.base)) + .set("Accept", "application/json") + .set("Content-Type", "application/sparql-query") + .set("X-TripleTrail-Client", "ui") + .send_string( + "SELECT * WHERE { ?a ?b . ?b ?c }", + ) + .unwrap(); + assert!(r.content_type().contains("json")); + // The Server header names TripleTrail, which the Explain plugin recognises (on every + // answer, so on the query the view reads it from too). + let server = |r: &ureq::Response| r.header("Server").unwrap_or_default().to_owned(); + assert!(server(&r).starts_with("TripleTrail/"), "{}", server(&r)); + let q = ureq::get(&format!("{}/plan/sparql", s.base)) + .query("query", "ASK {}") + .call() + .unwrap(); + assert!(server(&q).starts_with("TripleTrail/"), "{}", server(&q)); + let v: Value = serde_json::from_str(&r.into_string().unwrap()).unwrap(); + assert_eq!(v["rows"], 1); + assert!(v["plan"]["planning duration in seconds"].is_number()); + let root = &v["plan"]["plan"]; + fn walk(n: &Value, steps: &mut usize) { + assert!(n["name"].is_string(), "{n}"); + assert!(n["number of results"].is_number(), "{n}"); + assert!(n["duration in seconds"].is_number(), "{n}"); + *steps += 1; + for c in n["children"].as_array().unwrap() { + walk(c, steps); + } + } + let mut steps = 0; + walk(root, &mut steps); + assert!(steps >= 3, "{root}"); +} + #[test] fn a_dataset_created_with_a_union_default_graph_reads_every_graph() { let dir = temp_dir("union"); diff --git a/crates/tripletrail-server/ui/app.js b/crates/tripletrail-server/ui/app.js index b3b9fd6..e5a36c4 100644 --- a/crates/tripletrail-server/ui/app.js +++ b/crates/tripletrail-server/ui/app.js @@ -506,13 +506,79 @@ if (!matguiLoading) { matguiLoading = new Promise((resolve, reject) => { const s = el("script", { src: MATGUI + "yasgui.min.js" }); - s.onload = resolve; + s.onload = () => { teachExplainTripleTrail(); resolve(); }; s.onerror = () => reject(new Error("MatGUI could not be loaded from " + MATGUI)); document.head.append(s); }); } return matguiLoading; } + + // MatGUI's Explain view asks QLever, GraphDB, Stardog, Blazegraph or Neptune for a plan, and + // knows none of them here: it said "No engine recognised" and showed no plan. For this + // server's own endpoints it now asks TripleTrail's /explain, and shows the plan as a tree. + const explainUrlOf = (endpoint) => { + let u; + try { u = new URL(endpoint, location.href); } catch (e) { return null; } + if (u.origin !== location.origin || !/\/(sparql|query)\/?$/.test(u.pathname)) return null; + return u.origin + u.pathname.replace(/\/(sparql|query)\/?$/, "/explain"); + }; + const tripletrailEngine = { + id: "tripletrail", + label: "TripleTrail", + description: "The plan TripleTrail ran, with the rows and time of each step.", + needsRequestOptions: true, + buildRequest(query, endpoint) { + const url = explainUrlOf(endpoint); + if (!url) throw new Error("This endpoint is not on this TripleTrail server."); + return { query, accept: "application/json", endpoint: url }; + }, + parse(body) { return explainPlanOf(body); }, + }; + /** TripleTrail's explain JSON as the tree (or text) MatGUI's Explain view draws. */ + function explainPlanOf(body) { + let r; + try { r = JSON.parse(body); } catch (e) { throw new Error("TripleTrail did not return JSON."); } + const ms = (s) => (typeof s === "number" ? s * 1000 : undefined); + const summary = []; + if (typeof r.rows === "number") summary.push(`Result size: ${r.rows.toLocaleString("en-US")} rows`); + const planning = r.plan && ms(r.plan["planning duration in seconds"]); + if (planning !== undefined) summary.push(`Query planning: ${planning.toFixed(2)} ms`); + const sp = r.spatial || {}; + if (sp.filters || sp.joins) summary.push(`Spatial: ${sp.filters || 0} filters, ${sp.joins || 0} joins, ${sp.candidates || 0} candidates, index lookup ${(sp.lookup_ms || 0).toFixed(1)} ms`); + for (const d of sp.decisions || []) summary.push(`Spatial rewrite: ${d}`); + const node = (n) => ({ + label: String(n.name || "step").replace(/\s+/g, " ").trim(), + details: [], + rows: typeof n["number of results"] === "number" ? n["number of results"] : undefined, + timeMs: ms(n["duration in seconds"]), + children: (n.children || []).map(node), + }); + const root = r.plan && (r.plan.plan || (r.plan.name ? r.plan : null)); + if (root) return { kind: "tree", root: node(root), summary }; + if (r.restricted) summary.push("The plan is left out: you may read only some of the graphs, and the plan is chosen from all of them."); + return { kind: "text", text: summary.join("\n") || "No plan." }; + } + function teachExplainTripleTrail() { + const Yasr = window.Yasgui && window.Yasgui.Yasr; + const Explain = Yasr && Yasr.plugins && Yasr.plugins.Explain; + if (!Explain || Explain.tripletrail) return; + class TripleTrailExplain extends Explain { + resolveEngine(options) { + const found = super.resolveEngine(options); + return !found.engine && found.source === "none" && explainUrlOf(this.endpoint || "") + ? { engine: tripletrailEngine, source: "detected" } : found; + } + async runRequest(engine, req, signal) { + if (engine !== tripletrailEngine) return super.runRequest(engine, req, signal); + const headers = { ...viewAs.headers(), Accept: req.accept, "Content-Type": "application/sparql-query", "X-TripleTrail-Client": "ui" }; + const r = await fetch(req.endpoint, { method: "POST", headers, body: req.query, signal }); + return { status: r.status, headers: r.headers, content: await r.text() }; + } + } + TripleTrailExplain.tripletrail = true; + Yasr.registerPlugin("Explain", TripleTrailExplain); + } // A Workbench workspace is queried as "workspace:" (from the Workbench's Open in MatGUI). const WS = "workspace:"; const serviceOf = (name, service) => name.startsWith(WS) diff --git a/docs/guide/02-first-steps.md b/docs/guide/02-first-steps.md index b2786fa..0773b6a 100644 --- a/docs/guide/02-first-steps.md +++ b/docs/guide/02-first-steps.md @@ -140,6 +140,32 @@ line,sections,km 0,2,4 ``` +## See how a query ran + +After a query has run, the **Explain** tab of the results shows the plan TripleTrail ran. Its +**Engine** list reads **Detect (TripleTrail)**, and the **Execution plan** gives every step +(joins, sorts, triple patterns) with the rows it gave and the time it took, the slowest step +in orange. **Algebra** below it is the query as SPARQL algebra. The **Explain** button above +MatGUI gives the same plan in a dialog, with the decisions of the spatial index. + +The plan comes from `/ds/explain`, which takes a query like `/ds/query` does: + + +```sh +curl -s http://localhost:7878/ds/explain \ + --data-urlencode 'query=PREFIX ex: +SELECT ?code WHERE { ?station a ex:Station ; ex:code ?code } ORDER BY ?code' +``` + + +```text +{"rows":10, +"name":"Sort(ASC(?code))","number of results":10 +``` + +Each step has its `name`, `number of results`, `duration in seconds` and the steps under it +in `children`. + ## The same from the command line Every dataset answers at the same URLs as Apache Jena Fuseki, so any SPARQL client works with diff --git a/docs/server.md b/docs/server.md index 6136690..3744cdf 100644 --- a/docs/server.md +++ b/docs/server.md @@ -153,7 +153,10 @@ tripletrail serve --store oxigraph --location /data/tripletrail --dataset kg long-running geo functions. - `--cors ` (repeatable) allows cross-origin requests from those origins, `--cors` alone from every origin. Pages may send `Authorization`, `Content-Type`, `Accept` and `X-API-Key`, and - read `X-Result-Incomplete`, `X-Cache` and `X-Truncated` from answers. + read `X-Result-Incomplete`, `X-Cache`, `X-Truncated` and `Server` from answers. Every answer + carries `Server: TripleTrail/`, which names the engine so that query tools can + recognise it. (The web UI's Query page shows TripleTrail's plan in MatGUI's Explain view + without it.) - `--union-default-graph kg,build` (or `*`, `TRIPLETRAIL_UNION_DEFAULT_GRAPH`; `unionDefaultGraph=true` when creating a dataset over the admin API) makes the default graph of queries and updates the union of all graphs, as Fuseki's `tdb2:unionDefaultGraph`: rules @@ -2244,7 +2247,9 @@ then takes it out of the address bar. backup in one dialog. - **Query**: [MatGUI](https://github.com/Matdata-eu/Matgui) on the chosen dataset, with its table, map, chart and graph views, and **Explain**, which shows TripleTrail's plan with row counts, - timings and the spatial and range decisions. + timings and the spatial and range decisions. MatGUI's own **Explain** tab of the results asks + `/{ds}/explain` too for this server's endpoints (its Engine list reads "Detect (TripleTrail)"), + and draws the plan as a tree of steps with their rows and times. - **Map** (`/$/ui/map/{ds}`): the dataset's features on a map, a layer per collection (see [Vector tiles](#vector-tiles)), with a layer list, facets to filter each collection with their counts, and the features under a click. A feature's describe page opens in a panel