Skip to content

fix(server): query routes read a request's dataset the way the engine does - #2019

Merged
aaj3f merged 5 commits into
mainfrom
fix/query-route-dataset-checks
Oct 13, 2026
Merged

aaj3f merged 5 commits into
mainfrom
fix/query-route-dataset-checks

Conversation

@aaj3f

@aaj3f aaj3f commented Oct 5, 2026 •

Copy link
Copy Markdown
Contributor

What changes

Multi-query, SPARQL sub-queries. The envelope reads each SPARQL sub-query's dataset with the engine's own parse and dataset conversion, on the text the engine runs (i.e. with the envelope's PREFIX / BASE applied). That one set drives the distinct-ledger bound, the asOf check, the envelope snapshot and min-t. A ledger named in FROM by a prefixed name is counted and pinned to the envelope snapshot like one named by a bracketed IRI. A sub-query that doesn't parse, in either language, is reported under its alias with the parser's error, and its siblings still run. It never runs, so it reads nothing and adds no ledgers; the snapshot rewrite leaves its text untouched.

Ledger-scoped JSON-LD routes (/query/{ledger}, /stream/query/{ledger}, /explain/{ledger}). A single from object is read as the query parser reads it (@id, else id) and compared with the route's ledger by canonical ledger id:

  • Same-ledger spellings that used to be refused now succeed, e.g. {"@id": "mydb"} or {"@id": "urn:fluree:mydb:main"} on /query/mydb:main.
  • A from object that names no source ({}, or a non-string id) is refused in both execution lanes.

Strings, arrays, opts, ledger and fromNamed are read as before.

A request whose dataset names a ledger the route doesn't serve, or isn't allowed to read, is now refused as the single-query routes refuse it.

Implementation notes

  • fluree-db-api: validate_envelope_ledgers returns each SPARQL sub-query's dataset members alongside the distinct set, and validate_envelope keeps its signature. The SPARQL members come from parse_sparql_strict (the parse rule parse_and_validate_sparql now delegates to), followed by DatasetSpec::from_sparql_clause. sparql_subquery_text is the one place that builds the text the dispatcher runs, and the snapshot rewriter pins members by the same per-IRI reading. The separate IRI reader is removed.
  • fluree-db-api: DatasetSpec::default_graph_sources exposes the parser's reading of a from value, for the ledger route's check.
  • fluree-db-server: the multi-query route's read check and min-t wait use the validator's set. normalize_ledger_scoped_from reads a from object through default_graph_sources.
  • docs/api/multi-query.md: per-alias failures (parse or execution, both languages) and the 400 row.
  • docs/api/endpoints.md: how the ledger routes read a from object and a from string.

Tests

New (each fails on main):

  • multi_query_sparql_sibling_scope_matches_resolved_dataset
  • multi_query_snapshot_pins_every_ledger_a_sparql_sibling_reads (uses an asOf between two commits: the prefixed member is read at the snapshot)
  • ledger_route_from_object_is_read_as_the_parser_reads_it: table-driven, 24 from shapes in both lanes (@id, id, both, unknown keys, urn:, pins, graph selectors, sourceless objects)
  • ledger_route_from_object_check_covers_stream_and_explain
  • api unit tests: prefixed FROM counted, the dataset read from the dispatcher's text, a dataset clause that can't be read refused, a prefixed FROM pinned

Locks (pass on main and after):

  • multi_query_sub_query_min_t_covers_every_ledger_it_reads
  • multi_query_sparql_sibling_urn_spelling_is_read_checked
  • urn_spelling_in_a_dataset_is_read_checked

Per-alias parse failures (each fails with the change reverted):

  • multi_query_sub_queries_that_do_not_parse_are_reported_per_alias, plus its in-process twin in it_multi_query.rs: one sub-query per language that doesn't parse, partial, both errors listed
  • a_sparql_subquery_that_does_not_parse_has_no_members
  • sparql_with_a_recovered_parse_error_is_returned_unchanged: a parse error the parser recovers from, with its FROM ledger in the snapshot, comes back as written

Checks

  • cargo fmt --all -- --check
  • cargo clippy -p fluree-db-api -p fluree-db-server --all-targets --no-deps -- -D warnings, default features and --all-features
  • cargo test -p fluree-db-api -p fluree-db-server: 5249 passed, 0 failed
  • testsuite-sparql: cargo test --test w3c_sparql, 36 passed

Review round: at ddde98beb, fmt, clippy (default and --all-features) and the wasm32 clippy are clean, and the api (2,255) and server (706) tests pass. At b061c5fcd, fmt and clippy are clean and the multi-query tests pass (149: it_multi_query, the server's multi_query_integration, and the api's multi-query unit tests).

Multi-query: each SPARQL sub-query's ledgers are read from the text the dispatcher runs, with the engine's own parse and dataset conversion. That one set drives the distinct-ledger bound, the asOf check, the envelope snapshot and min-t, so a prefixed name in FROM is counted and pinned like a bracketed IRI. A SPARQL sub-query that does not parse is refused with the parser's error, as a single query is.

Ledger-scoped JSON-LD routes: a single from object is read as the dataset parser reads it (@id, else id) and compared with the route's ledger by canonical ledger id. Every spelling of the route's ledger is accepted; an object that names no source is refused in every execution lane.
@aaj3f aaj3f added bug Something isn't working as expected area:server HTTP surface, routes, error mapping, swagger, timeouts/admission, config graph labels Oct 5, 2026
@aaj3f
aaj3f requested review from bplatz and zonotope October 6, 2026 10:11

@zonotope zonotope left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think this change looks good and I don't have anything blocking merge besides one question.

My other comments are about docs. You can take or leave these suggestions, but I think we'd do well to tighten up our docs now. They are generally overly verbose, sometimes hard to follow, and filled with irrelevant information and blanket statements about other parts of the code, which invites skew when those sections change. I commented about a few examples, but there are many more instances like this that I came across.

Like I said, take or leave those suggestions. I don't see anything to hold back merge besides my question about the "from" value array form validation.

Comment thread docs/api/multi-query.md Outdated
A sub-query that fails while it runs is reported in `errors` like this. A
SPARQL sub-query that does not parse is different: the envelope cannot tell
which ledgers it reads, so the whole envelope is refused with `400 Bad
Request` and the parser's error, as a single query would be.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The second sentence is long enough to make it difficult to read. The ':' should be changed to a '.'. I think it would be even clearer if there was another sentence split at the last ',' along with converting the final clause beginning with "as a single ..." to a complete sentence.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Good call — that one had gotten pretty run-on. Split it the way you suggested in db0193efe (: → ., plus the extra break at the last comma so the "as a single …" part stands on its own as a sentence).

.unwrap_or_default();
let with_directives = apply_sparql_context(sparql, &directives);
let with_snapshot = apply_snapshot_to_sparql(&with_directives, snapshot);
// from the envelope context only. Validation read this

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

either "Validations read ..." or "Validation reads ..."

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yep, fixed to "Validation reads" in db0193efe.

Comment thread fluree-db-api/src/query/helpers.rs Outdated
/// Parse SPARQL text the way every query entry point does: an error-severity
/// diagnostic refuses the text even when the parser's error recovery produced
/// an AST. Callers that read a query's dataset before it runs (the multi-query
/// envelope) parse with this so they read the AST the engine will run.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This comment is more verbose than it needs to be, which makes it harder to skim to find the relevant parts.

We don't have to talk about what query entry points do here. First, we only need to document this particular function and secondly, the behavior of certain query entry points might change in the future leaving this comment stale. The same goes for what callers of this function like the multi-query envelope do with it. Insofar as that information is relevant, it should go on the doc comments of those callers themselves and not here.

Something like "Parse SPARQL query. Return an error if the parser produced any error severity diagnostics even if the parser's error recovery still produced an AST." would be a more concise comment without losing relevant information.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Agreed, and fair point on the skew risk — the comment was really describing callers rather than the function. Trimmed it down to just what parse_sparql_strict does (basically your wording) in db0193efe. I also went back through the rest of the comments and docs this PR added looking for the same pattern (describing callers or what other parts of the code do) and tightened those in the same commit.

/// context's `PREFIX` / `BASE` directives applied ([`apply_sparql_context`]).
/// Validation reads the sub-query's dataset from this text and the dispatcher
/// runs it, so the two read one dataset.
pub fn sparql_subquery_text(sparql: &str, envelope_context: Option<&JsonValue>) -> String {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is another verbose doc with irrelevant information that invites future skew. Something like "A sparql sub-query's text with the envelope context's PREFIX / BASE directives applied." is much shorter and still includes the relevant info.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Took your wording more or less verbatim in db0193efe — much easier to skim.

Comment thread fluree-db-server/src/routes/query.rs Outdated
// it as the dataset parser reads it — one source, named by `@id`
// or else `id` — and compare canonical ledger ids, as the read
// checks do, so every spelling of this ledger passes and no
// spelling of another one does. An object that names no source is

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This only covers the single-object form. The array arm on line 2481 still passes through unchecked. Is that intended?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Good eye, and yeah — that's intended, though I agree the asymmetry looks odd at first.

normalize_ledger_scoped_from is really just the "this from means this ledger" check for the single-reference forms: a bare string or a single {@id}/{id} object that names a different ledger is almost certainly a mistake on a /query/{L} route, so we turn it into the "Ledger mismatch" 400. The array (and fromNamed) arm is deliberately left alone because an array from is the multi-ledger / union form — "from": ["a:main", "b:main"] is the same mixed-dataset shape /query takes, and on the ledger route it just means "start from this ledger, and also union these". It flows straight to the connection/dataset parsing path, which reads the whole dataset. We actually lean on that — stream_query_integration::multi_ledger_from_streams_union posts from: ["strm:a","strm:b"] to /stream/query/strm:a and expects both ledgers back, so refusing cross-ledger arrays here would break a documented union.

Per-ledger authorization doesn't live in this function at all — every ledger a request actually names (array elements and fromNamed members included) is checked downstream by enforce_bearer_dataset_scope for a scoped bearer, and by per-ledger policy on the execution path. So ["other:main"] on /query/own:main with a token that can't read other still comes back 404, the same as the single-string form — I confirmed that across /query, /stream/query and /explain. The mismatch guard here is more of an intent/ergonomics check for the single-ref case than the authorization boundary.

Where I think you're right is the surface inconsistency: "from": "other:main" and {"id": "other:main"} are a 400, but ["other:main"] reads other. Access is checked the same way for both, but the difference is a little surprising. Making the array arm reject non-path ledgers too would be a real behavior change (it'd refuse the union form above), so I'd rather not fold it into this PR — it feels like it belongs with the whole-ledger-FROM semantics work in #1975, where we're already deciding what a FROM naming a ledger should mean on these routes. I'll pin it down there as part of #1975.

So it's intended, but it was a good question. The docs commit on this PR (db0193efe) now says that an array/fromNamed from is the multi-ledger form, where before that was only implied by the /query section.

Comment thread fluree-db-server/src/routes/query.rs Outdated
if base != base_path {
JsonValue::Object(ref m) => {
// Object form must name this ledger (time/graph selectors ok). Read
// it as the dataset parser reads it — one source, named by `@id`

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We don't need to talk about the dataset parser here. We can just describe what this function does and leave it at that.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Makes sense — it now just describes what normalize_ledger_scoped_from does, without the detour into the dataset parser (db0193efe).

@bplatz bplatz left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Approving: reading SPARQL sub-query datasets through the engine's own parse is the right fix, and I confirmed multi_query_snapshot_pins_every_ledger_a_sparql_sibling_reads fails with the snapshot rewriter reverted. Please review the inline comments before merging. The first two are the substantive ones: the string-from behaviour on the ledger routes doesn't match the new docs, and JSON-LD fromNamed isn't pinned to the envelope snapshot.

Comment thread docs/api/endpoints.md Outdated
**Other ledgers:**

If the body includes a ledger reference that targets a different ledger than `{ledger}`, the server returns `400 Bad Request` with a "Ledger mismatch" error.
- A single `from` (a string or an object), or a SPARQL `FROM` / `FROM NAMED`, that names a different ledger than `{ledger}` is a `400 Bad Request` "Ledger mismatch" error.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This holds for objects but not for every string. normalize_ledger_scoped_from still sends a string through looks_like_graph_selector_only first, which treats anything without a colon, or starting with urn:, as a graph inside the route's ledger. I added these to the ledger_route_from_object table on /query/own:main. All of them return 404 Graph not found: <...> in both lanes:

from expected by this doc got
"other" 400 Ledger mismatch 404 Graph not found
"urn:fluree:other:main" 400 Ledger mismatch 404 Graph not found
"own" 200 ({"@id": "own"} now is) 404 Graph not found
"urn:fluree:own:main" 200 ({"@id": "urn:fluree:own:main"} now is) 404 Graph not found

Nothing leaks, but the string and object forms of the same id now behave differently, and the doc says they match. Could the string arm compare scope_id against the route's ledger before falling back to the graph-selector heuristic? Or, if strings are deliberately out of scope here, narrow this line and file a follow-up.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

You're right, and I don't think the string arm can match the object arm here. A bare name or a urn:fluree: string can be a graph of the route's ledger or another ledger entirely, and only the ledger's graph registry can tell which, and this function doesn't have it.

#2007, which builds on this PR, routes normalize_ledger_scoped_from through one resolver that strings and objects both go through, with the route ledger's graph registry in hand. It checks the registry first and otherwise reads the string as a ledger address, so there:

  • other and urn:fluree:other:main should be a 400 naming the other ledger;
  • own and urn:fluree:own:main should read the route's ledger.

I'll add your four string rows as tests in #2007 when I rebase it onto this PR, so that behavior is pinned rather than just read off the code.

For this PR, I've narrowed the doc to what the code actually does (ddde98beb). A from object names the ledger in any spelling. A from string is a graph of the route's ledger when it's a keyword, an IRI or a bare name; otherwise it has to name the ledger as the path spells it.

let members: Vec<SubqueryLedger> = spec
.default_graphs
.iter()
.chain(&spec.named_graphs)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

SPARQL members now include FROM NAMED, but the JSON-LD equivalent is still missed. validate_jsonld_subquery and apply_snapshot_to_jsonld read only from, never fromNamed. A JSON-LD sub-query with "from": "mqa:x", "fromNamed": "mqa:y" and a graph clause on mqa:y returns mqa:y's rows, but the response's snapshot.ledgers lists only mqa:x. So mqa:y isn't pinned to the envelope snapshot, isn't covered by the min-t wait, and isn't counted toward the distinct-ledger bound. Access is fine: enforce_bearer_dataset_scope still refuses a token scoped to mqa:x alone.

This predates the PR, but it's the JSON-LD side of what this PR fixes for SPARQL. Reading JSON-LD datasets through DatasetSpec the way SPARQL now goes through from_sparql_clause would close it. Either fold it in or file it as Follow-up: #N.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Good catch. This is fixed in #2007, which builds on this PR; the change goes up with its rebase onto this one today. There, a JSON-LD sub-query's dataset is read through the dataset parser, so fromNamed members are:

  • counted against the distinct-ledger bound;
  • pinned to the envelope snapshot;
  • covered by the min-t wait, like SPARQL FROM NAMED members are here.

It comes with tests for the fromNamed case, both in-process and over the server.

Comment thread fluree-db-api/src/query/multi/mod.rs Outdated
};

let text = sparql_subquery_text(body, envelope_context);
let ast = crate::query::helpers::parse_sparql_strict(&text).map_err(unreadable)?;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Your call on which way to go here, but JSON-LD and SPARQL should share the behaviour. Right now a JSON-LD sub-query that fails to parse is reported under errors while its siblings still run (status: "partial"). A SPARQL sub-query that fails to parse refuses the whole envelope with a 400.

The per-alias form is cheap to keep for SPARQL. A sub-query that doesn't parse never runs, so it reads nothing, and leaving it out of the ledger set doesn't weaken the scope check. On parse failure, validate_sparql_subquery could return no members, and the dispatcher's strict parse would then report the error under that alias, as before this PR. If you'd rather refuse the envelope, that's fine too, as long as an unparseable JSON-LD sub-query is refused the same way and multi-query.md says so for both languages.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I went with per-alias for both, as you suggested (b8605b372):

  • A SPARQL sub-query that doesn't parse now has no members, so it's left out of the ledger set. The dispatcher reports the parse error under its alias, and the siblings still run.
  • A dataset clause that parses but can't be read (a bad time pin, say) still refuses the envelope, since validation can't tell what that alias would read.
  • The snapshot rewrite now leaves SPARQL that doesn't parse cleanly untouched (b061c5fcd), so validation and execution always read the same text the same way.

multi-query.md now says this for both languages. The in-process and server tests each send one sub-query per language that doesn't parse, and expect partial with both errors listed.

/// If prefixed names appear, they're passed through as-is and will likely fail
/// nameservice resolution unless the identifier happens to match.
fn iri_value_to_string(iri: &IriValue) -> String {
pub(crate) fn iri_value_to_string(iri: &IriValue) -> String {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nit: the doc comment above still says prefixed names "will likely fail nameservice resolution". With this PR, multi-query validation and the snapshot rewriter rely on this function to read FROM mq:p2 as ledger mq:p2, so the comment should describe that rather than call it accidental.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks, fixed (ddde98beb). The comment now says a prefixed name is read as written, so FROM mq:p2 names the ledger mq:p2, as FROM <mq:p2> does.

aaj3f added 3 commits October 12, 2026 08:20
… its alias

A SPARQL sub-query that does not parse reads nothing, so validation now
gives it no members. Its siblings run, and the parse error is reported
under its alias in `errors`, as for a JSON-LD sub-query that does not
parse. A dataset clause that parses but cannot be read still refuses the
envelope (`SparqlUnreadable`).

multi-query.md says this for both languages; the partial-failure example
is a parse error again.
The ledger-route docs say how a `from` string is read: a graph keyword,
an IRI or a bare name is a graph of the route's ledger; any other string
is a ledger address that must name the route's ledger as the path spells
it. A `from` object names the ledger in any spelling of its id.

`iri_value_to_string`'s doc says a prefixed name is read as written, so
`FROM mq:p2` names the ledger `mq:p2`.
…eanly

`apply_snapshot_to_sparql` returns the text unchanged when the parse has
any error, not only when it produced no AST. A sub-query with a parse
error now reaches execution as written, whatever the parser recovered.
@aaj3f
aaj3f requested a review from bplatz October 12, 2026 14:47
aaj3f added a commit that referenced this pull request Oct 12, 2026
A JSON-LD source object names its source by `@id`, or else `id`
(`dataset::source_object_id`, which the parser now reads through too).
The ledger-scoped resolver read only `@id`, so it could take an object
for a different source than the parser then read. It now reads the same
key: a single `from` naming another ledger by `id` is a 400 as with
`@id`, one naming this ledger by `id` reads it, and an object that names
no source is refused before any execution path runs.

This carries #2019's `from` object rule into the resolver the ledger
routes share. `DatasetSpec::default_graph_sources`, which the route used
for that rule, has no caller left and goes.
@aaj3f
aaj3f merged commit 3da440d into main Oct 13, 2026
29 of 30 checks passed
@aaj3f
aaj3f deleted the fix/query-route-dataset-checks branch October 13, 2026 17:06
aaj3f added a commit that referenced this pull request Oct 13, 2026
One conflict, in fluree-db-query/src/eval/compare.rs: #2044 made the
ordering comparison return a ValueOrder (a NaN operand compares false,
not as a type error), and this branch replaced the plain-string temporal
coercion with temporal::cmp_with_lexical. Kept #2044's ValueOrder and
double handling as they are; the coercion calls cmp_with_lexical and
returns ValueOrder::Ordered.
aaj3f added a commit that referenced this pull request Oct 13, 2026
Brings in #2019 and #2044. One conflict, in `eval/rdf.rs`, where both
sides added next to `fast_same_term_encoded_ids`: #2044's `same_term`
(two evaluated values are one term when equal, every NaN the one term
"NaN"^^xsd:double) is kept as it is, and `eval_same_term` calls it; this
branch's id comparison for encoded IRIs keeps its place ahead of both,
and answers only when an encoded IRI is on one side, so doubles always
reach `same_term`.
aaj3f added a commit that referenced this pull request Oct 13, 2026
Brings in #2019, #2044, #2048, #2049 and #2052 (main at 58b5323).

#2052 keys cross-ledger governance by the model ledger's head commit and
opens the model at that commit. Two files conflicted:

- tx.rs: this branch moved the stored-shapes pass into its own block
  (`stored_cache`), which #2052 edited in its old place. The block keeps
  this branch's shape, and its compiled-SHACL cache key carries #2052's
  commit id beside the model's t, as main's does. The shapes model opener
  and the cache key type merged without conflict.
- it_policy_cross_ledger.rs: both sides appended tests; both are kept.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area:server HTTP surface, routes, error mapping, swagger, timeouts/admission, config graph bug Something isn't working as expected

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants