Skip to content

feat: Turtle and N-Triples output for CONSTRUCT and DESCRIBE - #1940

Merged
bplatz merged 5 commits into
mainfrom
feat/construct-turtle-output
Sep 26, 2026
Merged

bplatz merged 5 commits into
mainfrom
feat/construct-turtle-output

Conversation

@bplatz

@bplatz bplatz commented Sep 25, 2026 •

Copy link
Copy Markdown
Contributor

Stacked on #1934 (Graph Store Protocol).

What this does

SPARQL CONSTRUCT and DESCRIBE results can now be returned as Turtle (text/turtle) or N-Triples (application/n-triples), alongside JSON-LD and RDF/XML. The format is the highest-q graph type in Accept; equal weights keep the header's order, and text/* means Turtle. The Graph Store GET from #1934 serves both formats, so a graph read as Turtle and PUT back unchanged commits nothing, blank nodes included.

Turtle output declares the query's PREFIXes (or a JSON-LD query's @context prefixes) and uses them. It groups each subject's triples, writes rdf:type as a, and writes numbers and booleans bare wherever they read back to the same value.

Query route (POST /query/{ledger})

  • One negotiation (GraphFormat / negotiate_graph_format in extract/headers.rs) replaces the RDF/XML-only substring check. Every path that served RDF/XML now serves any graph format.
  • Fix: the identity-scoped path (policy inputs, no FROM) returned 406 for RDF/XML. It now serves all graph formats, so a Graph Store GET by a restricted reader works in them.
  • A SELECT/ASK whose Accept admits only graph formats is a 406. Before, any mention of application/rdf+xml got a 406, even in a mixed header. The "both SPARQL XML and RDF/XML requested" conflict error is gone, since negotiation resolves it.
  • The connection-scoped route and multi-query envelopes return 406 for the new formats, as they already did for RDF/XML.

One set of RDF writing rules

Nine hand-written RDF writers had six string escapers and three IRI-escaping strategies (percent-encoding, \uXXXX, none), with some bugs. They now share one module:

  • fluree-graph-ir::syntax: string and IRI escaping in canonical N-Triples form, plus the Turtle PN_PREFIX / PN_LOCAL / BLANK_NODE_LABEL checks. It writes unescaped runs as whole slices, so a clean string costs one copy.
  • fluree-graph-format: format_turtle / format_ntriples over a Graph, and PrefixMap (moved here from export).
  • Export, the SHACL report, the memory store, the r2rml emitter, and the materialize parity keys now use it.

Behavior changes to note:

  • Export IRI escaping: a stored IRI containing a character <…> may not hold (such as a space) is now written as \uXXXX instead of %XX. Percent-encoding changed the IRI's identity on re-import; the escape reads back as the same IRI. The SHACL report and r2rml already did this.
  • Export prefixed names follow the full PN_LOCAL rule. ex:-a is no longer produced (it was invalid Turtle), and ex:a:b, ex:a%20b and non-ASCII local names now are. Context keys that aren't valid Turtle prefix names are skipped.
  • String escapes follow canonical N-Triples (\b and \f rather than \^H / \^L; C1 controls written raw).

CONSTRUCT fixes found on the way

  • RDF/XML wrote a stored blank node as rdf:about="_:fdb-…"; it is now rdf:nodeID.
  • A typed or language-tagged template literal ("salut"@fr, "5"^^xsd:long) lost its datatype or tag.

Performance and memory

CONSTRUCT used to decode an IRI (a format! plus a copy into an Arc) for every triple position, and to rebuild template constants for every row. Now template constants resolve once per query, and decoded IRIs and datatypes are cached per query, so the triples that repeat them share one Arc. The new writers format straight into one pre-sized string. New bench query_hot_construct_formats, 10k nodes / 48k triples, dev-fast profile, per query:

Format Time before Time after Allocated before Allocated after
JSON-LD 61 ms 47 ms 202 MB 160 MB
RDF/XML 42 ms 26 ms 133 MB 102 MB
Turtle – 23 ms – 92 MB
N-Triples – 26 ms – 103 MB

Query execution alone accounts for about 81 MB of each figure. CONSTRUCT's JSON-LD still builds a serde_json::Value DOM and remains the heaviest format.

Language tags

A Turtle or N-Triples language tag has no escape form, so an invalid one ended the literal: "hi"@en . <urn:x> <urn:p> "o" . # read back as an extra triple. JSON-LD ingest took @language verbatim, so this PR's Turtle output would have made that an injection.

  • fluree-graph-ir::syntax::is_lang_tag is the LANGTAG rule, with an optional RDF 1.2 base direction. The Turtle lexer uses the same rule.
  • JSON-LD @language, on values and on edge-annotation literals, is a 400 when invalid.
  • The writers check anyway, since a ledger may already hold a bad tag. format_turtle / format_ntriples refuse to write it, and so does export. Term's Display %-encodes it. The SHACL report's Turtle drops it.
  • RDF/XML rdf:nodeIDs are now always XML names; other labels are hex-encoded, as in Turtle. Graph-format negotiation prefers a specific media range over a wildcard at equal q.

SPARQL Service Description

A GET on /query or /query/{ledger} with no query parameter and no body now returns the endpoint's SPARQL Service Description, negotiated by Accept as JSON-LD, Turtle, N-Triples or RDF/XML. It was found missing while working on #1928 and lands here so it can use the Turtle output.

  • sd:endpoint is the requested URL, honouring X-Forwarded-Proto / X-Forwarded-Host.
  • Language and versions: SPARQL 1.2's sd:SPARQLQuery with sd:supportedVersion 1.0, 1.1, 1.2 and 1.2-basic, plus 1.1's sd:SPARQL11Query for older clients.
  • Result formats: SPARQL JSON, XML, CSV and TSV, JSON-LD, Turtle, N-Triples and RDF/XML.
  • Entailment: simple, since reasoning is opt-in per query.
  • No sd:feature: the default graph is not the union of the named graphs, and Fluree has no empty named graph.
  • Auth: the description sits behind the endpoint's own authentication.
  • Tests: a unit test for the builder in every format, and sparql_service_description.rs (HTTP): the ledger endpoint's triples, every format behind a proxy, a 406, the auth behaviour, and a GET with a query still running it. The three W3C service-description tests stay skip-registered because they need a running server.
  • Docs: docs/api/endpoints.md and docs/reference/compatibility.md.

Known limitation

Edge annotations are not in CONSTRUCT or Graph Store GET output in any format: a reifier's own triples come back, its link to the edge doesn't. This was already the case for JSON-LD and RDF/XML and is documented. Adding it takes template support in CONSTRUCT plus writer support; I plan to do it in the next PR in this stack.

Docs

  • Updated for the new formats: graph store, SPARQL output negotiation (endpoints), headers, multi-query, and a new graph-formats section in output formats and construct.
  • reference/compatibility.md, stale sections corrected:
    • SPARQL Update: graph management verbs, GRAPH ?g, and multi-operation requests are all supported.
    • Removed things that don't exist: the --strict-mode flag and the X-Fluree-API-Version header.
    • HTTP/TLS: the server speaks HTTP/1.1 only and doesn't terminate TLS.
    • Feature flag tables, export formats, roadmap, and the Rust toolchain version.
  • Annotation-output statements in turtle.md / edge-annotations.md: export writes annotations; CONSTRUCT doesn't.

Testing

  • HTTP (sparql_construct_jsonld_accept.rs): Turtle and N-Triples for CONSTRUCT, DESCRIBE, q weighting, the SELECT 406, the policy-scoped and FROM paths, and the connection-route 406. Bodies are parsed back with Fluree's Turtle parser.
  • Graph Store (graph_store_http.rs): N-Triples and Turtle GET; a Turtle GET then PUT of a graph with a blank node commits nothing.
  • API (it_query_construct.rs): a SPARQL / JSON-LD construct twin serializing to the same N-Triples; template literal tags and datatypes; stored blank nodes in all three text formats. The exhaustive output-format gate now classifies Turtle and N-Triples.
  • fluree-graph-format: both writers' output round-trips through the Turtle parser (escapes, shorthands, blank-node labels).
  • Each regression test was checked by breaking the fix: template datatype/tag, RDF/XML nodeID, the _: handling in the N-Triples writer, the identity-scoped graph path, the SELECT 406, quote escaping, and IRI space escaping. All seven tests failed with the fix broken.
  • cargo nextest over fluree-graph-ir, fluree-graph-format, fluree-db-r2rml, fluree-db-memory, fluree-db-api, fluree-db-server, fluree-db-cli: 5,760 tests. Two it_fwd_pack_compaction tests hit the 360 s timeout under load and pass on their own (176 s and 317 s).
  • cargo clippy --all-features --all-targets on the touched crates, the two wasm32 clippy gates, and cargo fmt --all. testsuite-sparql is not touched.

@bplatz bplatz added enhancement New feature or request area:server HTTP surface, routes, error mapping, swagger, timeouts/admission, config graph area:query Query execution, planning, fast paths, overlay, result formatting labels Sep 25, 2026
@bplatz
bplatz requested review from aaj3f and zonotope September 25, 2026 14:22
@bplatz
bplatz added this pull request to stack #1922 September 25, 2026 14:22
@bplatz
bplatz removed this pull request from stack #1922 September 25, 2026 18:27
@bplatz
bplatz force-pushed the feat/construct-turtle-output branch from 0c70f12 to b87e125 Compare September 25, 2026 19:15
@bplatz
bplatz added this pull request to stack #1947 September 25, 2026 19:15

@aaj3f aaj3f 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.

This is good @bplatz -- no real notes from me (though Claude found one escape/validation issue with literal suffixes e.g. language tag @ handling that you should look at below).


I'm quite excited about this one. The consolidation is the real story and it's underplayed in the description: nine writers with six escapers and three IRI strategies collapsing into fluree-graph-ir::syntax isn't tidying, it's fixing live output bugs — export was emitting ex:-a (invalid Turtle), turtle_sh_term was emitting sh: names with slashes in them, and export's percent-encoding was changing IRI identity on re-import where the \uXXXX form doesn't. The CONSTRUCT work underneath is equally good: template constants resolving once instead of per row and decoded IRIs shared across the triples that repeat them is a measured 30-40% win with the bench registered in all three places it needs to be, and the cst blank-node comment at construct.rs:199-221 is the most careful piece of serializer reasoning I've read in this repo. It also quietly unblocks #1934 — the identity-scoped 406 you remove at query.rs:2942 is what made RDF/XML GET dead for every authenticated Graph Store caller, and construct_graph_formats_on_policy_and_dataset_paths pins it (I mutated the fix and that test, and only that test, went red). The one thing blocking me is the language tag. push_literal_suffix writes @ plus the tag raw, and a LANGTAG has no escape form in Turtle or N-Triples, so an unvalidated tag doesn't get mangled — it terminates the literal. I built the case and ran it: one triple in, "hi"@en . <urn:injected> <urn:p> "pwned" . #, and the re-parsed document has two triples. The tag gets there unvalidated from jsonld.rs:1812, and RDF/XML escapes it while JSON-LD can't be broken out of, so this PR is what turns a lax-ingest gap into an injection. I'd want it closed at the source (validate @language against the LANGTAG production fluree-graph-turtle/src/lex/lexer.rs:114 already implements) and in the writer, so a serializer can never emit a document its own parser reads as something else. The one thing I'd hold it for is the language tag: push_literal_suffix writes @ + the tag raw, LANGTAG has no escape form in either grammar, and nothing validates the tag on the way in — so a crafted tag makes the output re-parse as extra triples, which I reproduced. It isn't only the new formats: validate.rs:301 renders a SHACL validation report's Turtle the same way, escaping the literal and interpolating the tag raw on the same line. Two sinks from one unvalidated input is why I'd fix it where the tag is accepted rather than in the writers.

Adherence to repo commitments:

  • Patterns/abstractions: ✔ Exactly the right altitude — lexical rules in the lowest shared crate, whole-graph writers beside the existing JSON-LD one, one GraphFormat negotiation replacing per-format substring checks. The only place "one set of rules" doesn't reach is blank-node labelling, where three policies now coexist (rdf_text hex-encodes, export writes verbatim, rdf_xml writes raw into rdf:nodeID).
  • Performance (speed first, memory second): ✔ A measured improvement, not a regression — per-row template rebuilds and per-position IRI decodes both eliminated (JSON-LD 61→47 ms, RDF/XML 42→26 ms, allocations down ~20%), with query_hot_construct_formats registered in Cargo.toml, regression-budget.json and the bench guide. No hot-path regression. The whole-graph materialization at graph_text.rs:32-33 is unchanged from before and tracked only partially by #1942.
  • Testing: ✔ All three new suites are genuinely wired (grp_query.rs:16, grp_query_sparql.rs:19, grp_http.rs:7) and I re-ran them: 110 unit tests in fluree-graph-format/fluree-graph-ir, 16 in sparql_construct_jsonld_accept, 5 in graph_store_http, all green with every new test name present. Two mutation checks confirmed the round-trip test and the identity-scoped fix are both load-bearing. testsuite-sparql green at this head and untouched.
  • Conventions: ✔ Two well-factored multi-line commits (the second exists purely to move the bench into the right category), clippy/fmt green in CI, and the docs go further than required — the compatibility.md de-staling is real, and I checked it rather than trusting it: --strict-mode and X-Fluree-API-Version genuinely don't exist anywhere in the tree, and there's no TLS or HTTP/2 in the server.

Verified locally at branch HEAD 0c70f12a4: cargo nextest run -p fluree-graph-format -p fluree-graph-ir --all-features (110/110), -p fluree-db-server --test grp_query -E 'test(/sparql_construct_jsonld_accept/)' (16/16), -p fluree-db-server --test grp_http -E 'test(/graph_store_http/)' (5/5); the language-tag injection reproduced with a temporary probe test; two mutation checks; worktree restored clean after each. CI at this exact SHA is fully green.

Just get the language tag closed before this merges and I'm happy — everything else on the list is small enough to fold in alongside it or wave off.

push_datatype: impl FnOnce(&mut String, &str),
) {
if let Some(lang) = language {
out.push('@');

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.

Blocking — an unvalidated language tag terminates the literal and injects triples into the serialized document. (Same hole at fluree-graph-ir/src/term.rs:484.)

push_literal_suffix writes out.push('@'); out.push_str(lang); with no escaping and no grammar check. Every other term component in this module goes through syntax::, but a LANGTAG has no escape mechanism in Turtle or N-Triples, so escaping isn't available — the tag has to be valid or the document is malformed. Nothing upstream guarantees that: JSON-LD ingest takes @language verbatim at fluree-db-transact/src/parse/jsonld.rs:1807-1812 (DatatypeConstraint::LangTag(Arc::from(lang))), datatype_constraint.rs:53 documents that LangTag "always succeeds", it is interned as a lang_id with no grammar check, and CONSTRUCT passes it straight through at fluree-db-api/src/format/construct.rs:315-320.

I ran it. A literal with the language tag en . <urn:injected> <urn:p> "pwned" . # serializes to

<http://example.org/alice> <http://example.org/label> "hi"@en . <urn:injected> <urn:p> "pwned" . # .

and re-parsing that through fluree_graph_turtle::parse yields 2 triples — the original plus <urn:injected> <urn:p> "pwned" ., which was never in the graph. Turtle output is identical in shape. End to end, the delivery is: PUT /v1/fluree/data/L?graph=G with a JSON-LD body carrying the tag (#1934), then GET the same graph with Accept: text/turtle, and anything that consumes the response — including a GET-then-PUT round trip back into Fluree — takes on the injected triple.

What makes this this PR's problem rather than a pre-existing one: RDF/XML escapes the tag (rdf_xml.rs:152-155) and JSON-LD puts it in a JSON string where it can't break out, so before this PR there was no output format a hostile tag could do anything in.

One more sink, which is why I'd put the weight on validating at ingest rather than escaping at the writer: fluree-db-api/src/validate.rs:301 — a file this PR does touch — builds a Turtle term for a SHACL validation report as format!("{}@{lang}", turtle_string(lex)). The asymmetry is visible on that one line: the lexical form goes through turtle_string, the tag is interpolated raw. So a tag crafted to break out reaches a second Turtle-producing path that has nothing to do with the new output formats, and any consumer parsing a validation report gets the same forged triples. There is no escape form for LANGTAG to add here either, which is the point — the only place this can be fixed once is where the tag is accepted.

I'd fix it at both ends. At the source, validate @language in jsonld.rs:1807 against the LANGTAG production the Turtle and SPARQL lexers already implement (fluree-graph-turtle/src/lex/lexer.rs:114-120 — [a-zA-Z]+ ('-' [a-zA-Z0-9]+)*) and reject a malformed tag with a 400, which closes it for every path including the ones that don't serialize. And in the writer, add syntax::is_lang_tag() next to is_pn_prefix / is_pn_local and make push_literal_suffix refuse rather than emit — a serializer should not be able to produce a document its own parser reads as something else, even if the data it was handed was already bad.

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, good find. Fixed at both ends in dfa3938.

  • Source: fluree-graph-ir::syntax::is_lang_tag implements LANGTAG (plus the RDF 1.2 --ltr/--rtl direction, which the Turtle lexer accepts and stores), and the Turtle lexer now uses the same rule. JSON-LD @language is checked at jsonld.rs and on edge-annotation literals, and an invalid tag is a 400. A Graph Store PUT carrying your tag is now 400 invalid language tag.
  • Writers: format_turtle / format_ntriples check every tag before writing and return InvalidLangTag rather than emit a bad one. That also covers tags already stored before this fix. Export's Turtle writer refuses the same way, and push_nt_term is no longer public. Term's Display can't fail, so it %-encodes an invalid tag: the output can fail to parse but can never read as more triples. The SHACL report at validate.rs:301 drops an invalid tag rather than failing the whole report.

Tests: is_lang_tag cases, your injection against both writers and Display, the ingest refusal, and the HTTP PUT. Each fails with its guard removed.

match subject {
// A stored blank node comes back as a `_:`-prefixed IRI.
Term::Iri(iri) if iri.starts_with("_:") => {
out.push_str(r#" rdf:nodeID=""#);

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.

Optional — rdf:nodeID gets XML-attribute escaping but no NCName check, so the one label class rdf_text.rs goes out of its way to handle is the one RDF/XML still emits raw. (Also :98, :130, :142.)

rdf_text.rs:199-208 hex-encodes any label that fails is_blank_node_label, and the module doc says why: "ids minted by old imports contain / and :". Those are exactly the labels the RDF/XML path now writes into rdf:nodeID="old/ledger:1", and rdf:nodeID takes an NCName — / and : aren't legal in one, and escape_attr_into only handles &, < and ".

So a CONSTRUCT over a legacy-import blank node produces parseable Turtle and unparseable RDF/XML from the same graph. Reusing syntax::is_blank_node_label plus the same x-prefixed hex fallback would make the three writers agree, which is what the PR's own "one set of RDF writing rules" framing promises. Minor and non-blocking — but if you agree it's right, I'd rather see it folded in here than lost in the backlog.

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.

Done in c4e1f21. rdf:nodeID now gets the label only when it's an XML name, and otherwise the same x plus hex fallback as the Turtle writer. That also covers digit-first labels, which Turtle allows but an NCName doesn't. There's a test with old/ledger:1 and 0.

@@ -899,7 +789,7 @@ fn write_turtle_iri_or_bnode<W: Write>(
if iri.starts_with("_:") {
w.write_all(iri.as_bytes())

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.

Optional — the export path kept its own blank-node policy, so the consolidation stops one caller short. (Also :1643.)

write_turtle_iri_or_bnode writes _:-prefixed labels verbatim, with a comment saying that's deliberate ("an export has to round-trip"). That reasoning made sense when export was the only Turtle writer; now rdf_text.rs solves the same round-trip requirement and stays parseable by hex-encoding the invalid ones. The result today is that fluree export --format turtle of a ledger with legacy-import blank nodes emits a document Fluree's own Turtle parser rejects, while CONSTRUCT of the same data doesn't.

Your code didn't introduce this — it predates the PR — but this is the PR that unified the other five callers, so it feels like the natural place. Happy to be told it belongs with a dedicated export pass instead.

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 it's the natural next step, but I split it out as #1956. Hex-encoding changes the label text in backup files, so it needs a decision on whether re-import must give each blank node the same stored identifier. That seemed worth its own review rather than riding in a feature PR.

Comment thread fluree-db-server/src/extract/headers.rs Outdated
})
.filter(|(q, _)| *q > 0.0)
.collect();
ranges.sort_by(|a, b| b.0.total_cmp(&a.0));

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.

Optional, more a question than a suggestion — media_ranges orders purely by q, so a more specific range loses to a wildcard at equal weight.

RFC 7231 §5.3.2 says media ranges are ordered by specificity first and q second; ranges.sort_by(|a, b| b.0.total_cmp(&a.0)) on a stable sort means Accept: */*, text/turtle resolves to JSON-LD where the spec says Turtle.

In practice this almost never bites — browsers put */* last with a lower q, curl sends */* alone, and the tests cover the realistic orderings — so I don't think it matters much. But this is a W3C-protocol-conformance PR, and a find_map over three specificity tiers (exact type, type/*, */*) within each q band would be maybe five lines. Genuinely fine to leave if you'd rather not churn the negotiation.

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.

Done, in c4e1f21: within a weight, an exact type beats type/*, which beats */*. Accept: */*, text/turtle now gets Turtle. I added it and text/*, application/rdf+xml to the negotiation test.

)));
}

let mut graph = instantiate_construct_graph(result, compactor)?;

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.

Optional, context rather than a finding — worth saying out loud that this PR doesn't stream and #1942 doesn't cover what's left.

instantiate_construct_graph + canonicalize() + a single pre-sized String means the whole graph exists twice in memory before the first byte ships, in all four formats. #1942 is scoped to replacing the JSON-LD serde_json::Value DOM, which is the worst case but not the shared one — the whole-graph materialization survives that fix.

Given #1934 makes "serialize the entire default graph" a one-line GET, it might be worth widening #1942's scope line, or noting in docs/query/output-formats.md that graph output is unpaged. Not asking for streaming in this PR.

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.

Added a "not streamed or paged" line to docs/query/output-formats.md; the Graph Store page already says GET is unpaged. I also left a scope note on #1942 that whole-graph materialization is shared by every graph format, not just the JSON-LD DOM.

@@ -190,490 +222,191 @@ fn row_blank(
blank

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.

fluree-db-api/src/format/construct.rs:199-221

Praise — this is the comment I'd point someone at to explain what careful serializer work looks like.

The cst prefix isn't "pick something unlikely" — it enumerates every sanctioned blank-node producer (fdb-…, b{n}, BNODE()'s two forms), asserts prefix-disjointness, then names the one case that isn't disjoint by construction (a remote SERVICE blank) and explains why runtime enforcement covers it, and finally says what goes wrong without the discipline: a mixed template silently merging a minted blank with a data blank, "a merge the isomorphism-based W3C CONSTRUCT suite cannot catch." That last clause is the whole reason the reasoning had to be written down rather than tested.

Commenting here because row_blank and its comment (lines 199-221) fall outside a diff hunk.

/// `%XX` sequences are allowed, since Turtle keeps them verbatim. Local names
/// that need a `\` escape (`/`, `#`, `?`, `(`, …) are rejected: the caller
/// writes the full `<iri>` instead, which every parser reads the same way.
pub fn is_pn_local(local: &str) -> bool {

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.

Praise — is_pn_local validating %XX as a separate pass before the name-character check is the thing a quick implementation gets wrong.

The test table proves it (a%2 and a%zz rejected, a%20b and a:b accepted). Together with matches_name:174-180 this replaces an escaper that was emitting ex:-a — invalid Turtle — from the export path.

assert!(ttl.contains("_:fdb-1 ex:p true .\n"), "{ttl}");
}

/// Both writers' output parses back to the same triples, escapes and

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.

Praise — output_round_trips_through_the_turtle_parser is the right test for this PR.

Serialize → parse → compare, over a fixture that deliberately includes a quote, a newline, a backslash, a tab, U+0007, U+0085, an emoji, an IRI containing a space and <c>, a stored _:fdb-1, a legacy old/ledger:1 label, a lang tag, a custom datatype and NaN.

I mutation-checked it (dropped the " escape from escape_string) and it goes red along with four others. It's also what makes the GET-Turtle-then-PUT-back-commits-nothing assertion in graph_store_http.rs credible end to end.

Comment thread fluree-db-api/Cargo.toml
name = "query_overlay_matrix"
harness = false

[[bench]]

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.

Praise — bench registered in all three places it needs to be.

The [[bench]] entry here, the regression-budget.json:101-105 entry, and the query_hot row in docs/contributing/benches.md — and the second commit exists purely to rename it into the right category. That's the part people forget and the nightly workspace_reconcile test catches later.

@bplatz
bplatz force-pushed the feat/construct-turtle-output branch 2 times, most recently from 07d1a74 to c204f54 Compare September 25, 2026 21:07
@bplatz
bplatz force-pushed the feat/construct-turtle-output branch 2 times, most recently from 67c7545 to baac02b Compare September 25, 2026 21:31
@bplatz
bplatz force-pushed the feat/construct-turtle-output branch 3 times, most recently from ac189dc to 15400f9 Compare September 25, 2026 23:13
@bplatz
bplatz force-pushed the feat/construct-turtle-output branch from 15400f9 to 2dffc1b Compare September 25, 2026 23:31
@bplatz
bplatz force-pushed the feat/construct-turtle-output branch from 2dffc1b to 0ab7ae7 Compare September 25, 2026 23:37
@bplatz
bplatz force-pushed the feat/construct-turtle-output branch from 0ab7ae7 to 785338d Compare September 25, 2026 23:52
@bplatz

bplatz commented Sep 26, 2026

Copy link
Copy Markdown
Contributor Author

To add in this PR: SPARQL 1.1 Service Description. It was found while working on #1928 and listed there under "Not in this PR".

A GET on a SPARQL query endpoint with no query parameter should return an RDF description of the service using the sd: vocabulary: an sd:Service with its sd:endpoint, supported languages and result formats, and the default dataset. Today it returns nothing of the kind.

Why here: the spec only requires some RDF serialization, and should-level content negotiation. With this PR's Turtle and N-Triples output, the description can be served in whatever Accept asks for (Turtle, N-Triples, JSON-LD or RDF/XML) using the serializers already in place.

The three W3C tests (returns-rdf, has-endpoint-triple, conforms-to-schema) are in the SPARQL11_SERVICE_DESCRIPTION skip register in testsuite-sparql/tests/registers/mod.rs. They need a running server, so coverage here would be HTTP tests.

@bplatz
bplatz force-pushed the feat/construct-turtle-output branch from 785338d to 5ad8c89 Compare September 26, 2026 00:45
@bplatz
bplatz force-pushed the feat/construct-turtle-output branch 2 times, most recently from 33c8c41 to 4b5828b Compare September 26, 2026 01:06
@bplatz
bplatz force-pushed the feat/construct-turtle-output branch 3 times, most recently from e532570 to 1f8980d Compare September 26, 2026 02:27
Base automatically changed from feat/graph-store-protocol to main September 26, 2026 02:59
SPARQL CONSTRUCT and DESCRIBE results can now be serialized as Turtle
(`text/turtle`) or N-Triples (`application/n-triples`), chosen by the
highest-q graph format in `Accept`. The Graph Store `GET` serves both, so a
graph read as Turtle and PUT back commits nothing. Graph formats are also
served on the identity-scoped (policy) query path, which refused RDF/XML;
a SELECT whose Accept admits only graph formats is a 406.

Writers:
- `fluree-graph-ir::syntax`: one set of string and IRI escapers (canonical
  N-Triples; `\uXXXX` for characters an IRIREF forbids, which reads back as
  the same IRI) and the Turtle PN_PREFIX / PN_LOCAL / BLANK_NODE_LABEL
  checks.
- `fluree-graph-format`: `format_turtle` / `format_ntriples` over a `Graph`,
  and `PrefixMap` (moved from export).
- Export, the SHACL report, the memory store, r2rml and materialize now use
  the shared escapers instead of their own. Export's IRI escaping moves from
  percent-encoding to `\uXXXX`, and its prefixed names follow the full
  PN_LOCAL rule.

CONSTRUCT:
- Template constants resolve once, and decoded IRIs and datatypes are
  shared across the triples that repeat them instead of allocated per use.
- A typed or language-tagged template literal keeps its datatype or tag.
- RDF/XML writes a stored blank node as `rdf:nodeID`, not `rdf:about`.

New bench `query_construct_formats` measures each graph format.
Rename `query_construct_formats` to `query_hot_construct_formats` (the
bare `query` category is reserved for fluree-db-query micro-benches), add
its regression budget, and list it under `query_hot` in the bench guide.
@bplatz
bplatz force-pushed the feat/construct-turtle-output branch from 1f8980d to 5239f25 Compare September 26, 2026 03:00
A GET on /query or /query/{ledger} with no `query` parameter and no body
now returns the endpoint's SPARQL Service Description instead of an
error, negotiated by Accept as JSON-LD, Turtle, N-Triples or RDF/XML.

It describes the service node with its sd:endpoint (the requested URL,
honouring X-Forwarded-Proto/-Host), and the SPARQL query language both
ways: SPARQL 1.2's sd:SPARQLQuery with sd:supportedVersion 1.0 through
1.2, plus sd:SPARQL11Query for older clients. It also lists the result
formats the query routes negotiate and simple entailment, since
reasoning is opt-in. It claims no sd:feature: the default graph is not
the union of the named graphs, and Fluree has no empty named graph.

The description sits behind the endpoint's own authentication. The
three W3C service-description tests stay in the skip register because
they need a running server; HTTP tests cover what they check.
…ters

A Turtle or N-Triples language tag has no escape form, so it must be
valid. JSON-LD ingest took `@language` verbatim and the RDF text writers
wrote `@` plus the tag raw. A tag like `en . <urn:x> <urn:p> "o" . #`
ended the literal, and the output read back as an extra triple.

- `fluree-graph-ir::syntax::is_lang_tag`: `LANGTAG`, optionally with an
  RDF 1.2 base direction. The Turtle lexer now uses the same rule.
- Ingest: JSON-LD `@language`, on values and on edge-annotation
  literals, is a 400 when invalid.
- Writers: `format_turtle` / `format_ntriples` refuse a graph holding an
  invalid tag, which may already be stored, and export's Turtle writer
  does the same. `Term`'s Display %-encodes one, since it cannot fail.
  The SHACL report's Turtle drops an invalid tag rather than failing
  the report.
- `rdf:nodeID` takes an XML name, but legacy import labels (`/`, `:`) and
  digit-first labels were written raw, so the same graph produced valid
  Turtle and invalid RDF/XML. Labels that are not XML names are
  hex-encoded behind an `x`, as the Turtle writer does.
- Graph format negotiation breaks ties at equal `q` by specificity (a
  type, then `type/*`, then `*/*`), so `Accept: */*, text/turtle` gets
  Turtle.
- `docs/query/output-formats.md`: graph output is not streamed or paged.
@bplatz

bplatz commented Sep 26, 2026

Copy link
Copy Markdown
Contributor Author

@aaj3f thanks. The language tag is closed at both ends in dfa3938: @language is validated at ingest (400), and every text writer refuses an invalid tag, since a ledger may already hold one. c4e1f21ab covers the RDF/XML node IDs, Accept specificity and the unpaged-output doc note. Export's blank-node labels are #1956. Details are on each thread.

This PR also gained the SPARQL Service Description since your approval (66f75cc, the section in the description). A GET on a query endpoint with no query returns it, and it advertises SPARQL 1.1 and 1.2. That commit hasn't been reviewed yet, so a look would be appreciated.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area:query Query execution, planning, fast paths, overlay, result formatting area:server HTTP surface, routes, error mapping, swagger, timeouts/admission, config graph enhancement New feature or request

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants