Repository navigation
SPARQL query parameters over HTTP; parse each request once - #2475
Conversation
The SPARQL query endpoints take `params`, a JSON object binding variables
to values for one request, from the URL or a form-encoded body. It binds as
QueryExecutionOptions::with_params does for embedded callers, on every
SPARQL route and response lane: /query/{ledger} (JSON, XML, graph formats,
tracked, policy-scoped, FROM datasets), /query, /explain and /stream/query.
A variable left unbound widens the match rather than failing, so `params`
is refused wherever it would not bind: on JSON-LD and Cypher requests, on
the update endpoints, when it is not a JSON object, when it appears twice,
and when it names a variable the query never mentions.
SPARQL parses now go through a process-wide cache keyed on query text
(FLUREE_SPARQL_AST_CACHE, default 512 entries, queries up to 8 KiB), as
Cypher's do. It holds only parses the API accepts, so a text that fails to
parse or validate is parsed afresh and keeps its exact diagnostics, and
parameters are substituted into a per-request copy. The server's routing
parses (dataset clause, query form, dataset ledgers) read the same cache,
so a request is parsed once instead of twice even when its text is new.
explain_connection_sparql_with_opts_and_params joins
explain_connection_sparql_with_opts for the connection explain route.
Times each phase of a SPARQL query through Fluree::query and the server's result formatters — parse, lower, setup, rewrite, plan, run, result assembly, format — split at the engine's own tracing spans within one run. Reports elapsed time per phase, weighted by an optional query mix, for sizing reusable preparation and result encoding.
The process-wide SPARQL parse cache made every request take its global lock twice — the server's routing parse inserted, execution read it back — and, once full, evict an older parse with its whole syntax tree freed inside the lock. Under concurrency that cost more than the parse it saved: BSBM explore at 100M with 32 clients ran 2–4% below main, every query slower in proportion. The server's routing parse now travels with the request instead: QueryExecutionOptions::with_sparql_parse hands it to the run, which reads it when the text matches and parses otherwise. A request is still parsed once, and nothing is shared between requests — no lock, no eviction. The cross-request cache is gone (and FLUREE_SPARQL_AST_CACHE with it); reuse across requests for repeated texts is a separate change, to be measured on its own. SparqlParse holds the text, the parser's output and whether the API accepts it (no error diagnostic, valid), checked once. The run paths that read a request's SPARQL — view, tracked, graph source, dataset, stream, connection — take the handed-off parse.
aaj3f
left a comment
There was a problem hiding this comment.
@bplatz this is nice, and handing the routing parse to the run is the right design: one parse per request, nothing shared between requests. On a box the server gets up to 32% faster per query on the ledger route and up to 54% on the connection route, with the embedded path flat, and Claude checked the hand-off can only be read for its exact text.
My reading is that this makes params a Fluree extension to the SPARQL Protocol on every query route and turns a stray params on JSON-LD, Cypher or any write endpoint from silently ignored into a 400. I think that's right, since ignoring it widens the match, but I'd like your confirmation that it's the intended surface.
One must below: an AgentJson resume query drops the bindings, so page two silently answers the unbound question.
Full review below:
✅ Approving to unblock: please get the AgentJson resume fix in before merging. params binds on every SPARQL lane with a 400 everywhere it can't, the hand-off is sound, and every server lane gets measurably faster with nothing measurably slower; the one must is a few lines.
Before merging:
fluree-db-server/src/routes/query.rs:935: an AgentJsonresumemust not dropparams(withhold it, or carry the bindings).
Notes:
- This is at least the fifth instance where a binding silently stops binding and the unbound variable widens the match:
96cdb4b39(a blank-node parameter),fafb66c58(a name given twice),bd3797dcc(a trailingVALUES),main's silent drop of?params=that this PR's refusals close (on a box,mainletDELETE WHERE { ?s ex:name ?n }with?params=delete all 2,000 names), and the AgentJsonresumehere. A server-side request type that carries the text and its bindings together (built once at the edge, taken by execution, the resume and the advisory headers) would make the next one unrepresentable. Not this PR; the point fix is right here. - fwiw Claude measured the cache revision before this commit and saw what your body describes, worse on the embedded host: 16 concurrent callers sending fresh texts went from 24.1 to 71.2 µs per query. At
4f527e30dthe same row is flat againstmain(24.3 → 24.1 µs), so I'm glad the cache is out and a cross-request one is left to its own measured change. - My #2466 overlaps three files here.
git merge-treeis clean, the merged tree passescargo check -p fluree-db-api -p fluree-db-server -p fluree-db-sparql --testson a box, and #2466's newrules-frompragma lives in the query text, so the hand-off's text match covers it. Either can merge first, with no rebase work either way. - The new title's "parse each request once" holds on the ledger route; on the connection route a request still parses for its ledger refresh (and a bearer's scope check) before the routing parse, and the tracked lane once more (see the
query.rs:833note). paramson the update endpoints is left as a follow-up; the400keeps that safe in the meantime, so I'm on board with it waiting.
Adherence: patterns ✔ · performance ✔ · deployment targets ✔ · testing ⚠️ · conventions ✔ · verification
- Patterns/abstractions: ✔ binds through
QueryExecutionOptions::with_params, and the hand-off rides the same carrier (with_sparql_parse) instead of a side channel; JSON-LD's400matches the embedded API's refusal (query/mod.rs:194-204), and Cypher keeps its bodyparams. - Performance (speed first, memory second): ✔ mean per-query latency on a c7i.4xlarge, three interleaved rounds: ledger route −11% to −32% (one overlapping 16-client row aside), connection route −20% to −54%, tracked connection route −3% to −19% (instructions −12% to −53% across the three); embedded flat (instructions −1.6% to +0.4%). The only rows that read worse overlap between rounds or come with fewer instructions. No process-wide state.
- Deployment targets: ✔ nothing is shared between requests any more, so a per-process or serverless host gets the same behaviour; an embedder's run without a hand-off does
main's work; wasm32 compiles in CI. - Testing:
⚠️ 17 server tests and 5 hand-off/parse-count unit tests run and pass in CI'stestjob on4f527e30d; both update refusals and the hand-off's text guard are pinned (mutations go red); the AgentJson lane, connection stream and connection explain are not (mutations stay green). - Conventions: ✔ thorough multi-line commit bodies, including why the cache went; CI
fmtandclippygreen; endpoint and SPARQL docs updated, and the configuration row removed with the knob.
Verified at 4f527e30d: CI test (16,586 passed), clippy, fmt, wasm32, wasm-smoke, testsuite-sparql green; on a c7i.4xlarge Claude ran a base/head A/B across the ledger route, the connection route (plain and tracked) and Fluree::query (four workloads, one and 16 clients, three interleaved rounds), perf stat instruction counts, mutation checks of the new server and hand-off tests, probes of the AgentJson resume, the result cache and the write-endpoint refusals, and a merge-and-check against #2466.
Approving so you can merge once the resume fix is in; the optional notes are small, and I'd rather see them folded in here than lost in the backlog.
| .execution_options(query_execution_options(&state)) | ||
| .execution_options( | ||
| params | ||
| .execution_options(&state) |
There was a problem hiding this comment.
Blocking: an AgentJson response cut short by Fluree-Max-Bytes hands back a resume query without the request's params, so following it runs the unbound query.
The AgentJson lanes build their context from the raw text (sparql_text: Some(sparql.to_string()) at query.rs:859 on this route, and at :3857 and :4151 on the ledger route). When the byte budget cuts a response, truncation_resume_and_message (fluree-db-api/src/format/agent_json.rs:161) turns that text into the next-batch query, pinning FROM <ledger@t:N> and rewriting OFFSET/LIMIT, and the envelope says "Use the query below to retrieve the next batch." The binding was never in the text, so it isn't in the resume either, and nothing in the envelope mentions it.
Claude reproduced it on a box at 4f527e30d: GET /v1/fluree/query with SELECT ?s ?n FROM <ab:main> WHERE { ?s ex:name ?n ; ex:cat ?c } ORDER BY ?s, params={"c": {"@id": "http://ex.org/c3"}}, Accept: application/vnd.fluree.agent+json and fluree-max-bytes: 600 returns 20 rows, all in ex:c3, with hasMore: true and resume: "… FROM <ab:main@t:1> WHERE { ?s ex:name ?n ; ex:cat ?c } ORDER BY ?s OFFSET 20 LIMIT 100". Running that resume as told returns 100 rows, 94 of them outside ex:c3 (the bound query has 100 rows in all, the unbound one 2,000). An agent paging through the answer silently switches to a wider question on page two, which is exactly what the PR's 400s exist to prevent.
The narrowest fix is to withhold resume when the request carries params and say in message to re-send the same params with OFFSET/LIMIT, or to emit the bindings beside it (say "resumeParams": {…}) so a client can send both back. Either is a few lines: one field on AgentJsonContext that truncation_resume_and_message checks, set at the three constructions, plus a test that pins it (the AgentJson lanes have none yet; see the test note below). Commenting here because query.rs:859 and agent_json.rs aren't in this diff.
| // agent-json and plain paths both need the AST, the advisory header is | ||
| // derived from the same parse rather than a third one, and each | ||
| // execution below is handed it rather than parsing again. | ||
| let parsed = fluree_db_api::parse_sparql_shared(&sparql); |
There was a problem hiding this comment.
More of a suggestion than a must: a few run paths still parse instead of reading the hand-off, all on the connection route. The five tracked connection paths take options but call parse_and_validate_sparql(sparql, None) (fluree-db-api/src/query/connection.rs:923, :986, :1032, :1080, :1137), and build_stream_dataset_for_sparql (view/stream_query.rs:352) gets no options to read. Before this routing parse, the route also parses for its ledger refresh (:813) and, with a bearer token, for scope authorization (:807 → :664). Both could read their ledger ids off parsed.ast() if the parse moved up a few lines. The commit message lists tracked and stream among the paths that take the hand-off; on the ledger route they do.
None of this is correctness, since is_of makes a missed hand-off a re-parse and nothing worse. On the box, the tracked connection lane spends 4.52 M instructions per 1.3 KB query against 3.74 M untracked, about one parse more, and its latency gain over main is 3–19% where the untracked lane's is 20–54%. If you agree, I'd rather see these folded in now than lost in the backlog.
One way to make the next run path unable to miss it: give QueryExecutionOptions the parse method (options.parse_sparql(sparql, params) that always consults the hand-off) and keep the bare parse_and_validate_sparql for option-less callers only. Forgetting the hand-off then means not compiling. Commenting here because connection.rs:923 and view/stream_query.rs:352 aren't in this diff.
| } | ||
|
|
||
| #[tokio::test] | ||
| async fn explain_plans_the_bound_query() { |
There was a problem hiding this comment.
This is minor and non-blocking, but three of the binding sites aren't pinned by any test here. Claude mutation-checked them on the box at 4f527e30d: unbinding the AgentJson lane (query.rs:935, adding .with_params(Default::default())), the connection stream route (stream_query.rs:154, the same) or the connection explain route (query.rs:4358 → None) leaves all 17 tests green. Removing either update refusal turns params_on_an_update_are_rejected_and_nothing_changes red, as the body says.
A test each for AgentJson on /query (which can pin the resume fix too), /stream/query and /explain with a FROM would close it. If you agree it's right, I'd rather see these folded in now than lost in the backlog.
| } | ||
|
|
||
| /// [`SparqlParse::new`], shared between a request's routing and its run. | ||
| pub fn parse_sparql_shared(sparql: &str) -> SharedSparqlParse { |
There was a problem hiding this comment.
This is so minor, but parse_sparql_shared is new public API that still carries the cache's name. It's now Arc::new(SparqlParse::new(..)), and nothing is shared beyond one request. Since it isn't on main yet, we may want to drop it (callers write Arc::new(SparqlParse::new(&text))) or name it for what it does (parse_sparql_for_request, say) before embedders start depending on it.
| &self.output.diagnostics | ||
| } | ||
|
|
||
| fn is_of(&self, sparql: &str) -> bool { |
There was a problem hiding this comment.
Really nice call to key the hand-off on the exact text: an options value that travels into a subquery, a SERVICE body or any other text can't apply the wrong tree, and a missed hand-off degrades to a re-parse rather than a wrong answer. Claude checked the guard is load-bearing: dropping the is_of filter at :560 turns a_handed_off_parse_of_other_text_is_ignored red. Keeping the fields private so a caller can't hand over a parse that lies about being accepted is a nice touch too.
parse_sparql_shared was named for the parse cache it once fronted. It had become Arc::new(SparqlParse::new(..)), shared by nothing beyond the one request that hands its parse to the run. It is not on main yet, so it goes before anything depends on it: the server's four routing parses write the Arc directly. SharedSparqlParse stays as the type with_sparql_parse takes.
When Fluree-Max-Bytes cut an AgentJson response, the envelope offered a resume query built from the request's text: its FROM pinned to @t:N, OFFSET and LIMIT rewritten. A binding sent as params is not in the text, so following that query ran the unbound one, and a client paging through the answer silently switched to a wider question on page two. AgentJsonContext gains binds_params, which the server's three AgentJson constructions set from the request. A bound request's truncated response gives no resume query. Its message says to re-send the query with the same params, the @t: pin (or @time: on each FROM for several ledgers) and the next OFFSET and LIMIT. An empty params object binds nothing, so its resume query stands. The new server test sends an AgentJson query with params on the connection route (untracked and tracked), the ledger route, and the ledger route's dataset lane. Each checks that only the bound rows come back and that a cut response has no resume and points to the params. Turning the flag off at any construction site, or unbinding either connection AgentJson lane, makes it fail. The output-formats and endpoints docs describe the omission. AgentJsonContext's fields are public, so an embedder that builds it without ..Default::default() has to add the new field.
The connection route parsed a request's text up to four times before running it. The bearer scope check and the ledger refresh each parsed it to read its dataset ledgers, ahead of the routing parse that is handed to the run. The five tracked connection paths then ignored the hand-off and parsed again, as did the stream route's dataset build. The routing parse now comes first on /query and /stream/query, and the scope check and the refresh read their ledger ids from it. parsed_sparql_dataset_ledgers gives the same answer and the same error as sparql_dataset_ledgers, from that parse. QueryExecutionOptions::parse_sparql parses through the hand-off. Every run path that holds options now parses through it, the tracked connection paths included, so a new one cannot skip the hand-off by calling the bare parse. build_stream_dataset_for_sparql_with_options takes the options, and build_stream_dataset_for_sparql keeps its signature and delegates to it. A unit test counts parses: with a parse handed over, the tracked connection query and the stream dataset build parse nothing more, and each fails with its old parse restored. A new scope test pins the stream route's read check, which no test covered. A request with a Fluree-Min-T header or an @t: pin still parses for its min-t requirements, which several routes without a parse share.
Three binding sites had no test: unbinding them left every params test green. The connection /stream/query route now has its own case, which fails when its plan options drop params. The explain test covers each lane a FROM selects: the connection route at the head, its dataset lane, and the ledger route's connection lane. The connection route reaches its dataset lane only through a time-suffixed fluree-ledger header, since a dataset's ledger ids carry no time, so that case sends one. Unbinding any of the four explain binding sites, these three or the ledger route's own, fails a test.
Addressed in 44419a5: withheld, with the
Addressed in ee1d791.
Follow-up: #2480, linked from the PR body. |
The query routes took bindings as one `params` request parameter, a JSON object of JSON-LD values. Other SPARQL servers share a different convention: one `$name` parameter per variable, whose value is an RDF term. A client written for them sent `$name=<term>` here and had it ignored, so its query ran unbound and matched more than it asked for. The query routes now read `$name=<term>` from the URL or a form body, and `params` is gone; it never reached main. A `params` parameter is refused with a 400 that names the `$name` form, since a Cypher body spells its bindings that way. fluree_db_sparql::param_from_term reads one term with the SPARQL lexer and returns the JSON-LD form substitute_params already takes, so every rule stays as it was: an unknown or self-assigned variable is a 400, and a binding substitutes into the parsed query. Accepted values: - a full IRI in angle brackets; - a quoted literal, with an optional @language or ^^<datatype>; - a bare number or boolean, keeping the datatype it would have in the query text; - a stored node's _:fdb- id. A prefixed name is refused, since no prefix applies. Each variable may be bound once. The update endpoints refuse `$name` parameters, from the URL or a form body, as they refused `params`. Bindings never change the query text, so the request's one parse is still handed to the run. A unit test counts parses: a bound request with a parse handed over parses nothing more, and fails if bindings force a re-parse. The server tests now send `$name` (encoded as %24, and raw once). New cases check that a number matches by value and keeps its datatype (DATATYPE($v)), that a value must be one full term, that a variable binds once, and that `params` is refused. The AgentJson truncation message asks to re-send the same variable bindings. The SPARQL, endpoint and output-format docs describe the parameter.
8f9b943 to
1a43b67
Compare
Intended in substance, with one change: bindings now use the |
Every surviving row merged its interval into the batch envelope, but the envelope is read only to decide whether a walked index covers the batch or to build one. Once walking is off for a condition it has no index, so each batch goes to probes and the envelope was built for nothing. The envelope (and the all-numeric check) is now built only while walking is still allowed, and from the batch's distinct intervals rather than once per row: rows with the same bound operands share one interval, so a fixed-anchor batch merges once. Every distinct interval belongs to a kept row, so an empty list is what says no row is left to check; probes keep the exact per-row bounds as before.
The rows of a join repeat the values on one side of it - a product's label and comment on every one of its feature rows - and the SPARQL Results XML writer decoded and escaped each of them again per row. Each column now remembers the encoded value it last rendered and where that text sits in the output; a cell holding the same value copies the text. One comparison per cell, nothing hashed or allocated per row. Datatype attributes are decoded and escaped once per datatype per response instead of once per literal.
Brings #2471 (performance docs; PatternEstimate::Reducer and the leaflet cache's R1/R2 entries removed) and #2475 (SPARQL $name parameters over HTTP, one parse per request, the range semijoin envelope skip and the SPARQL XML repeated-cell copy). Conflicts: - planner.rs: Reducer is never built on next either; take main's removal and keep next's link pins on the remaining arms. - leaflet_cache.rs, lib.rs: drop R1/R2, LeafletCacheKey and their tests; keep next's stages, ranged/byte leaf entries, fence pool and its tests, and drop the region labels from next's occupancy kinds. - sparql_xml.rs: take main's CellWriter; TermKey's list place is next's packed u64, and next's triple-term rendering moves into CellWriter::write_term. - index-format.md: main's SPOT o_type sentence with next's o_i text. - performance.md: next's leaflet directory paragraph (stored row groups, routing keys widened over history). main's new XML test awaits genesis_ledger, which is async on next.
Summary
$nameparameter per variable, whose value is an RDF term ($author=<http://example.org/le-guin>,$year=1969), from the URL or a form-encoded body. This is the convention other SPARQL servers share, so a client written for them now binds here instead of having its bindings ignored. A value is a full IRI in angle brackets, a quoted literal with an optional@languageor^^<datatype>, a bare number or boolean (keeping the datatype it would have in the query), or a stored node's_:fdb-…id. It substitutes exactly asQueryExecutionOptions::with_params, which embedded callers already had, through the same JSON-LD forms.QueryExecutionOptions::with_sparql_parsehands it to the run, which reads it when the text matches and parses otherwise. On the connection routes the bearer scope check and the ledger refresh read the same parse, and the tracked lanes and the stream dataset build take the hand-off. Nothing is shared between requests: no cache, lock or eviction. A request with aFluree-Min-Theader or an@t:pin still parses once more for its freshness requirement.Where
$namebinds, and where it is refusedA variable left unbound widens the match instead of failing, so a
$namebinding either binds or gets a400. It is never ignored.$namebindings/query/{ledger}, every response lane: JSON, SPARQL Results XML, graph formats, tracked, policy-scoped,FROMdatasets/query(connection route),/explain,/stream/queryFluree-Max-Bytesresumequery, since it is built from the text and would run unbound. Themessagesays to re-send the same bindings with the@t:pin and the nextOFFSET/LIMIT400: JSON-LD takes values in the query; Cypher sends{"cypher": …, "params": …}as its body400: otherwiseDELETE WHERE { ?s ex:name $name }would delete every name400params(a Cypher body's spelling)400naming the$nameformWhy not a parse cache
An earlier revision of this PR shared parses through a process-wide cache keyed on query text. Each request then took its global lock twice: routing inserted, execution read it back. Once the cache was full, each request also evicted an older parse inside the lock. At 32 clients on BSBM explore at 100M, that cost more than the parse it saved (2–4% below
main). Handing the parse to the run keeps the single parse without any shared state. Reusing parses across requests for repeated texts is left to a separate, measured change.API
fluree_db_sparql::param_from_termreads one$namevalue as the JSON-LD formsubstitute_paramstakes.fluree_db_api::SparqlParseparses a request's SPARQL and checks it as the API would. A caller that inspects a query before running it hands the parse over withQueryExecutionOptions::with_sparql_parse(Arc::new(SparqlParse::new(&text)));parsed_sparql_dataset_ledgersreads its dataset ledgers.explain_connection_sparql_with_opts_and_paramssits besideexplain_connection_sparql_with_opts, andbuild_stream_dataset_for_sparql_with_optionsbesidebuild_stream_dataset_for_sparql; neither existing signature changes.AgentJsonContextgainsbinds_params. Its fields are public, so an embedder that builds it without..Default::default()has to add it.Tests
fluree-db-server/tests/sparql_protocol_query_params.rscovers each transport (GET, formPOST, directPOSTwith URL bindings,$raw and as%24) and each route and lane above. It also checks every refusal, that a number matches by value and keeps its datatype, and that an update sent with a binding changes nothing. One query text is run with two bindings and then none, to show a binding never outlives its request.resume. It covers the connection stream route and each explain lane aFROMselects, too.query::helperstests cover the hand-off: a matching parse is read instead of parsing, a parse of other text is ignored, a rejected parse reports the same errors as a fresh one, and parameters bind into a copy. Aquery::connectiontest counts parses: with a parse handed over, the tracked connection query and the stream dataset build parse nothing more.ledger_scope_authpins the stream route's bearer read check, which now reads the routing parse.DELETE WHEREcommits and deletes every name.Also
fluree-db-api/examples/sparql_phase_profile.rstimes each phase of a SPARQL query (parse, lower, plan, run, format, …) throughFluree::query, split at the engine's own tracing spans. It reports elapsed time per phase, weighted by a query mix, to size reusable preparation and result encoding. Benchmark results from a full-duration BSBM run will follow on this PR.Follow-up: #2480 (
$namebindings on the update endpoints; the embedded API already supports update parameters).